84 public const MOTION_THRESHOLD = 0.00001;
85 protected const STEP_CLIP_MULTIPLIER = 0.4;
87 private const TAG_FIRE =
"Fire";
88 private const TAG_ON_GROUND =
"OnGround";
89 private const TAG_FALL_DISTANCE =
"FallDistance";
90 private const TAG_CUSTOM_NAME =
"CustomName";
91 private const TAG_CUSTOM_NAME_VISIBLE =
"CustomNameVisible";
92 public const TAG_POS =
"Pos";
93 public const TAG_MOTION =
"Motion";
94 public const TAG_ROTATION =
"Rotation";
96 private static int $entityCount = 1;
102 return self::$entityCount++;
109 protected array $hasSpawned = [];
118 protected ?array $blocksAround =
null;
124 protected bool $forceMovementUpdate =
false;
125 private bool $checkBlockIntersectionsNextTick =
true;
128 public bool $onGround =
false;
132 private float $health = 20.0;
133 private int $maxHealth = 20;
135 protected float $ySize = 0.0;
136 protected float $stepHeight = 0.0;
137 public bool $keepMovement =
false;
139 public float $fallDistance = 0.0;
140 public int $ticksLived = 0;
141 public int $lastUpdate;
142 protected int $fireTicks = 0;
144 private bool $savedWithChunk =
true;
146 public bool $isCollided =
false;
147 public bool $isCollidedHorizontally =
false;
148 public bool $isCollidedVertically =
false;
150 public int $noDamageTicks = 0;
151 protected bool $justCreated =
true;
155 protected float $gravity;
156 protected float $drag;
157 protected bool $gravityEnabled =
true;
161 protected bool $closed =
false;
162 private bool $closeInFlight =
false;
163 private bool $needsDespawn =
false;
167 protected bool $networkPropertiesDirty =
false;
169 protected string $nameTag =
"";
170 protected bool $nameTagVisible =
true;
171 protected bool $alwaysShowNameTag =
false;
172 protected string $scoreTag =
"";
173 protected float $scale = 1.0;
175 protected bool $canClimb =
false;
176 protected bool $canClimbWalls =
false;
177 protected bool $noClientPredictions =
false;
178 protected bool $invisible =
false;
179 protected bool $silent =
false;
181 protected ?
int $ownerId =
null;
182 protected ?
int $targetId =
null;
184 private bool $constructorCalled =
false;
187 if($this->constructorCalled){
188 throw new \LogicException(
"Attempted to call constructor for an Entity multiple times");
190 $this->constructorCalled =
true;
191 Utils::checkLocationNotInfOrNaN($location);
193 $this->timings = Timings::getEntityTimings($this);
195 $this->size = $this->getInitialSizeInfo();
196 $this->drag = $this->getInitialDragMultiplier();
197 $this->gravity = $this->getInitialGravity();
199 $this->
id = self::nextRuntimeId();
204 $this->boundingBox =
new AxisAlignedBB(0, 0, 0, 0, 0, 0);
205 $this->recalculateBoundingBox();
210 $this->motion = Vector3::zero();
213 $this->resetLastMovements();
215 $this->networkProperties =
new EntityMetadataCollection();
217 $this->attributeMap =
new AttributeMap();
218 $this->addAttributes();
220 $this->initEntity($nbt ??
new CompoundTag());
222 $this->getWorld()->addEntity($this);
224 $this->lastUpdate = $this->
server->getTick();
226 $this->scheduleUpdate();
229 abstract protected function getInitialSizeInfo() : EntitySizeInfo;
246 public function getNameTag() : string{
247 return $this->nameTag;
250 public function isNameTagVisible() : bool{
251 return $this->nameTagVisible;
254 public function isNameTagAlwaysVisible() : bool{
255 return $this->alwaysShowNameTag;
266 public function setNameTag(
string $name) : void{
267 $this->nameTag = $name;
268 $this->networkPropertiesDirty =
true;
271 public function setNameTagVisible(
bool $value =
true) : void{
272 $this->nameTagVisible = $value;
273 $this->networkPropertiesDirty =
true;
276 public function setNameTagAlwaysVisible(
bool $value =
true) : void{
277 $this->alwaysShowNameTag = $value;
278 $this->networkPropertiesDirty =
true;
281 public function getScoreTag() : ?string{
282 return $this->scoreTag;
285 public function setScoreTag(
string $score) : void{
286 $this->scoreTag = $score;
287 $this->networkPropertiesDirty =
true;
290 public function getScale() : float{
294 public function setScale(
float $value) : void{
296 throw new \InvalidArgumentException(
"Scale must be greater than 0");
298 $this->scale = $value;
299 $this->setSize($this->getInitialSizeInfo()->scale($value));
302 public function getBoundingBox() : AxisAlignedBB{
303 return $this->boundingBox;
306 protected function recalculateBoundingBox() : void{
307 $halfWidth = $this->size->getWidth() / 2;
309 $this->boundingBox =
new AxisAlignedBB(
310 $this->location->x - $halfWidth,
311 $this->location->y + $this->ySize,
312 $this->location->z - $halfWidth,
313 $this->location->x + $halfWidth,
314 $this->location->y + $this->size->getHeight() + $this->ySize,
315 $this->location->z + $halfWidth
319 public function getSize() : EntitySizeInfo{
323 protected function setSize(EntitySizeInfo $size) : void{
325 $this->recalculateBoundingBox();
326 $this->networkPropertiesDirty =
true;
334 return $this->noClientPredictions;
346 $this->noClientPredictions = $value;
347 $this->networkPropertiesDirty =
true;
350 public function isInvisible() : bool{
351 return $this->invisible;
354 public function setInvisible(
bool $value =
true) : void{
355 $this->invisible = $value;
356 $this->networkPropertiesDirty =
true;
359 public function isSilent() : bool{
360 return $this->silent;
363 public function setSilent(
bool $value =
true) : void{
364 $this->silent = $value;
365 $this->networkPropertiesDirty =
true;
372 return $this->canClimb;
379 $this->canClimb = $value;
380 $this->networkPropertiesDirty =
true;
387 return $this->canClimbWalls;
394 $this->canClimbWalls = $value;
395 $this->networkPropertiesDirty =
true;
402 return $this->ownerId;
409 return $this->ownerId !== null ? $this->
server->getWorldManager()->findEntity($this->ownerId) : null;
419 $this->ownerId =
null;
420 }elseif($owner->closed){
421 throw new \InvalidArgumentException(
"Supplied owning entity is garbage and cannot be used");
423 $this->ownerId = $owner->getId();
425 $this->networkPropertiesDirty =
true;
432 return $this->targetId;
440 return $this->targetId !== null ? $this->
server->getWorldManager()->findEntity($this->targetId) : null;
449 if($target === null){
450 $this->targetId =
null;
451 }elseif($target->closed){
452 throw new \InvalidArgumentException(
"Supplied target entity is garbage and cannot be used");
454 $this->targetId = $target->getId();
456 $this->networkPropertiesDirty =
true;
463 return $this->savedWithChunk;
471 $this->savedWithChunk = $value;
476 ->setTag(self::TAG_POS, new
ListTag([
481 ->setTag(self::TAG_MOTION, new
ListTag([
486 ->setTag(self::TAG_ROTATION, new
ListTag([
488 new
FloatTag($this->location->pitch)
491 if(!($this instanceof
Player)){
492 EntityFactory::getInstance()->injectSaveId(get_class($this), $nbt);
494 if($this->getNameTag() !==
""){
495 $nbt->setString(self::TAG_CUSTOM_NAME, $this->getNameTag());
496 $nbt->setByte(self::TAG_CUSTOM_NAME_VISIBLE, $this->isNameTagVisible() ? 1 : 0);
500 $nbt->
setFloat(self::TAG_FALL_DISTANCE, $this->fallDistance);
501 $nbt->setShort(self::TAG_FIRE, $this->fireTicks);
502 $nbt->setByte(self::TAG_ON_GROUND, $this->onGround ? 1 : 0);
504 $nbt->setLong(VersionInfo::TAG_WORLD_DATA_VERSION, VersionInfo::WORLD_DATA_VERSION);
509 protected function initEntity(CompoundTag $nbt) : void{
510 $this->fireTicks = $nbt->getShort(self::TAG_FIRE, 0);
512 $this->onGround = $nbt->getByte(self::TAG_ON_GROUND, 0) !== 0;
514 $this->fallDistance = $nbt->getFloat(self::TAG_FALL_DISTANCE, 0.0);
516 if(($customNameTag = $nbt->getTag(self::TAG_CUSTOM_NAME)) instanceof StringTag){
517 $this->setNameTag($customNameTag->getValue());
519 if(($customNameVisibleTag = $nbt->getTag(self::TAG_CUSTOM_NAME_VISIBLE)) instanceof StringTag){
521 $this->setNameTagVisible($customNameVisibleTag->getValue() !==
"");
523 $this->setNameTagVisible($nbt->getByte(self::TAG_CUSTOM_NAME_VISIBLE, 1) !== 0);
528 protected function addAttributes() : void{
532 public function attack(EntityDamageEvent $source) : void{
533 if($this->isFireProof() && (
534 $source->getCause() === EntityDamageEvent::CAUSE_FIRE ||
535 $source->getCause() === EntityDamageEvent::CAUSE_FIRE_TICK ||
536 $source->getCause() === EntityDamageEvent::CAUSE_LAVA
542 if($source->isCancelled()){
546 $this->setLastDamageCause($source);
548 $this->setHealth($this->getHealth() - $source->getFinalDamage());
551 public function heal(EntityRegainHealthEvent $source) : void{
553 if($source->isCancelled()){
557 $this->setHealth($this->getHealth() + $source->getAmount());
560 public function kill() : void{
561 if($this->isAlive()){
564 $this->scheduleUpdate();
578 protected function onDeathUpdate(int $tickDiff) : bool{
582 public function isAlive() : bool{
583 return $this->health > 0;
586 public function getHealth() : float{
587 return $this->health;
594 if($amount == $this->health){
599 if($this->isAlive()){
600 if(!$this->justCreated){
606 }elseif($amount <= $this->getMaxHealth() || $amount < $this->health){
607 $this->health = $amount;
609 $this->health = $this->getMaxHealth();
613 public function getMaxHealth() : int{
614 return $this->maxHealth;
617 public function setMaxHealth(
int $amount) : void{
618 $this->maxHealth = $amount;
621 public function setLastDamageCause(EntityDamageEvent $type) : void{
622 $this->lastDamageCause = $type;
625 public function getLastDamageCause() : ?EntityDamageEvent{
626 return $this->lastDamageCause;
629 public function getAttributeMap() : AttributeMap{
630 return $this->attributeMap;
633 public function getNetworkProperties() : EntityMetadataCollection{
634 return $this->networkProperties;
637 protected function entityBaseTick(
int $tickDiff = 1) : bool{
640 if($this->justCreated){
641 $this->justCreated =
false;
642 if(!$this->isAlive()){
647 $changedProperties = $this->getDirtyNetworkData();
648 if(count($changedProperties) > 0){
649 $this->sendData(
null, $changedProperties);
650 $this->networkProperties->clearDirtyProperties();
655 if($this->checkBlockIntersectionsNextTick){
656 $this->checkBlockIntersections();
658 $this->checkBlockIntersectionsNextTick =
true;
660 if($this->location->y <= World::Y_MIN - 16 && $this->isAlive()){
661 $ev =
new EntityDamageEvent($this, EntityDamageEvent::CAUSE_VOID, 10);
666 if($this->isOnFire() && $this->doOnFireTick($tickDiff)){
670 if($this->noDamageTicks > 0){
671 $this->noDamageTicks -= $tickDiff;
672 if($this->noDamageTicks < 0){
673 $this->noDamageTicks = 0;
677 $this->ticksLived += $tickDiff;
682 public function isOnFire() : bool{
683 return $this->fireTicks > 0;
686 public function setOnFire(
int $seconds) : void{
687 $ticks = $seconds * 20;
688 if($ticks > $this->getFireTicks()){
689 $this->setFireTicks($ticks);
691 $this->networkPropertiesDirty =
true;
694 public function getFireTicks() : int{
695 return $this->fireTicks;
702 if($fireTicks < 0 || $fireTicks > 0x7fff){
703 throw new \InvalidArgumentException(
"Fire ticks must be in range 0 ... " . 0x7fff .
", got $fireTicks");
705 if(!$this->isFireProof()){
706 $this->fireTicks = $fireTicks;
707 $this->networkPropertiesDirty =
true;
711 public function extinguish() : void{
712 $this->fireTicks = 0;
713 $this->networkPropertiesDirty =
true;
716 public function isFireProof() : bool{
720 protected function doOnFireTick(
int $tickDiff = 1) : bool{
721 if($this->isFireProof() && $this->isOnFire()){
726 $this->fireTicks -= $tickDiff;
728 if(($this->fireTicks % 20 === 0) || $tickDiff > 20){
729 $this->dealFireDamage();
732 if(!$this->isOnFire()){
749 public function canCollideWith(
Entity $entity) : bool{
750 return !$this->justCreated && $entity !== $this;
753 public function canBeCollidedWith() : bool{
754 return $this->isAlive();
757 protected function updateMovement(
bool $teleport =
false) : void{
758 $diffPosition = $this->location->distanceSquared($this->lastLocation);
759 $diffRotation = ($this->location->yaw - $this->lastLocation->yaw) ** 2 + ($this->location->pitch - $this->lastLocation->pitch) ** 2;
761 $diffMotion = $this->motion->subtractVector($this->lastMotion)->lengthSquared();
763 $still = $this->motion->lengthSquared() == 0.0;
764 $wasStill = $this->lastMotion->lengthSquared() == 0.0;
765 if($wasStill !== $still){
767 $this->setNoClientPredictions($still);
770 if($teleport || $diffPosition > 0.0001 || $diffRotation > 1.0 || (!$wasStill && $still)){
771 $this->lastLocation = $this->location->asLocation();
773 $this->broadcastMovement($teleport);
776 if($diffMotion > 0.0025 || $wasStill !== $still){
777 $this->lastMotion = clone $this->motion;
779 $this->broadcastMotion();
783 public function getOffsetPosition(Vector3 $vector3) : Vector3{
787 protected function broadcastMovement(
bool $teleport =
false) : void{
788 NetworkBroadcastUtils::broadcastPackets($this->hasSpawned, [MoveActorAbsolutePacket::create(
790 $this->getOffsetPosition($this->location),
791 $this->location->pitch,
792 $this->location->yaw,
793 $this->location->yaw,
800 ($this->onGround ? MoveActorAbsolutePacket::FLAG_GROUND : 0)
805 protected function broadcastMotion() : void{
806 NetworkBroadcastUtils::broadcastPackets($this->hasSpawned, [SetActorMotionPacket::create($this->
id, $this->getMotion(), tick: 0)]);
809 public function getGravity() : float{
810 return $this->gravity;
813 public function setGravity(
float $gravity) : void{
814 Utils::checkFloatNotInfOrNaN(
"gravity", $gravity);
815 $this->gravity = $gravity;
818 public function hasGravity() : bool{
819 return $this->gravityEnabled;
822 public function setHasGravity(
bool $v =
true) : void{
823 $this->gravityEnabled = $v;
826 protected function applyDragBeforeGravity() : bool{
830 protected function tryChangeMovement() : void{
831 $friction = 1 - $this->drag;
833 $mY = $this->motion->y;
835 if($this->applyDragBeforeGravity()){
839 if($this->gravityEnabled){
840 $mY -= $this->gravity;
843 if(!$this->applyDragBeforeGravity()){
848 $friction *= $this->getWorld()->getBlockAt((
int) floor($this->location->x), (
int) floor($this->location->y - 1), (
int) floor($this->location->z))->getFrictionFactor();
851 $this->motion =
new Vector3($this->motion->x * $friction, $mY, $this->motion->z * $friction);
854 protected function checkObstruction(
float $x,
float $y,
float $z) : bool{
855 $world = $this->getWorld();
856 if(count($world->getBlockCollisionBoxes($this->boundingBox)) === 0){
860 $floorX = (
int) floor($x);
861 $floorY = (int) floor($y);
862 $floorZ = (int) floor($z);
864 $diffX = $x - $floorX;
865 $diffY = $y - $floorY;
866 $diffZ = $z - $floorZ;
868 if($world->getBlockAt($floorX, $floorY, $floorZ)->isSolid()){
869 $westNonSolid = !$world->getBlockAt($floorX - 1, $floorY, $floorZ)->isSolid();
870 $eastNonSolid = !$world->getBlockAt($floorX + 1, $floorY, $floorZ)->isSolid();
871 $downNonSolid = !$world->getBlockAt($floorX, $floorY - 1, $floorZ)->isSolid();
872 $upNonSolid = !$world->getBlockAt($floorX, $floorY + 1, $floorZ)->isSolid();
873 $northNonSolid = !$world->getBlockAt($floorX, $floorY, $floorZ - 1)->isSolid();
874 $southNonSolid = !$world->getBlockAt($floorX, $floorY, $floorZ + 1)->isSolid();
881 $direction = Facing::WEST;
884 if($eastNonSolid && 1 - $diffX < $limit){
886 $direction = Facing::EAST;
889 if($downNonSolid && $diffY < $limit){
891 $direction = Facing::DOWN;
894 if($upNonSolid && 1 - $diffY < $limit){
896 $direction = Facing::UP;
899 if($northNonSolid && $diffZ < $limit){
901 $direction = Facing::NORTH;
904 if($southNonSolid && 1 - $diffZ < $limit){
905 $direction = Facing::SOUTH;
908 if($direction === -1){
912 $force = Utils::getRandomFloat() * 0.2 + 0.1;
914 $this->motion = match($direction){
915 Facing::WEST => $this->motion->withComponents(-$force,
null,
null),
916 Facing::EAST => $this->motion->withComponents($force,
null,
null),
917 Facing::DOWN => $this->motion->withComponents(
null, -$force,
null),
918 Facing::UP => $this->motion->withComponents(
null, $force,
null),
919 Facing::NORTH => $this->motion->withComponents(
null,
null, -$force),
920 Facing::SOUTH => $this->motion->withComponents(
null,
null, $force),
928 public function getHorizontalFacing() : int{
929 $angle = fmod($this->location->yaw, 360);
934 if((0 <= $angle && $angle < 45) || (315 <= $angle && $angle < 360)){
935 return Facing::SOUTH;
937 if(45 <= $angle && $angle < 135){
940 if(135 <= $angle && $angle < 225){
941 return Facing::NORTH;
947 public function getDirectionVector() : Vector3{
948 $y = -sin(deg2rad($this->location->pitch));
949 $xz = cos(deg2rad($this->location->pitch));
950 $x = -$xz * sin(deg2rad($this->location->yaw));
951 $z = $xz * cos(deg2rad($this->location->yaw));
953 return (
new Vector3($x, $y, $z))->normalize();
956 public function getDirectionPlane() : Vector2{
957 return (new Vector2(-cos(deg2rad($this->location->yaw) - M_PI_2), -sin(deg2rad($this->location->yaw) - M_PI_2)))->normalize();
968 public function onUpdate(
int $currentTick) : bool{
973 $tickDiff = $currentTick - $this->lastUpdate;
975 if(!$this->justCreated){
976 $this->
server->getLogger()->debug(
"Expected tick difference of at least 1, got $tickDiff for " . get_class($this));
982 $this->lastUpdate = $currentTick;
984 if($this->justCreated){
985 $this->onFirstUpdate($currentTick);
988 if(!$this->isAlive()){
989 if($this->onDeathUpdate($tickDiff)){
990 $this->flagForDespawn();
996 $this->timings->startTiming();
998 if($this->hasMovementUpdate()){
999 $this->tryChangeMovement();
1001 $this->motion = $this->motion->withComponents(
1002 abs($this->motion->x) <= self::MOTION_THRESHOLD ? 0 :
null,
1003 abs($this->motion->y) <= self::MOTION_THRESHOLD ? 0 :
null,
1004 abs($this->motion->z) <= self::MOTION_THRESHOLD ? 0 :
null
1007 if($this->motion->x != 0 || $this->motion->y != 0 || $this->motion->z != 0){
1008 $this->move($this->motion->x, $this->motion->y, $this->motion->z);
1011 $this->forceMovementUpdate =
false;
1014 $this->updateMovement();
1016 Timings::$entityBaseTick->startTiming();
1017 $hasUpdate = $this->entityBaseTick($tickDiff);
1018 Timings::$entityBaseTick->stopTiming();
1020 $this->timings->stopTiming();
1022 return ($hasUpdate || $this->hasMovementUpdate());
1025 final public function scheduleUpdate() : void{
1027 throw new \LogicException(
"Cannot schedule update on garbage entity " . get_class($this));
1029 $this->getWorld()->updateEntities[$this->id] = $this;
1032 public function onNearbyBlockChange() : void{
1033 $this->setForceMovementUpdate();
1034 $this->scheduleUpdate();
1042 $this->scheduleUpdate();
1050 $this->forceMovementUpdate = $value;
1052 $this->blocksAround =
null;
1060 $this->forceMovementUpdate ||
1061 $this->motion->x != 0 ||
1062 $this->motion->y != 0 ||
1063 $this->motion->z != 0 ||
1068 public function getFallDistance() : float{ return $this->fallDistance; }
1070 public function setFallDistance(
float $fallDistance) : void{
1071 $this->fallDistance = $fallDistance;
1074 public function resetFallDistance() : void{
1075 $this->fallDistance = 0.0;
1078 protected function updateFallState(
float $distanceThisTick,
bool $onGround) : ?float{
1079 if($distanceThisTick < $this->fallDistance){
1082 $this->fallDistance -= $distanceThisTick;
1086 $this->fallDistance = 0;
1088 if($onGround && $this->fallDistance > 0){
1089 $newVerticalVelocity = $this->onHitGround();
1090 $this->resetFallDistance();
1091 return $newVerticalVelocity;
1103 public function getEyeHeight() : float{
1104 return $this->size->getEyeHeight();
1107 public function getEyePos() : Vector3{
1108 return new Vector3($this->location->x, $this->location->y + $this->getEyeHeight(), $this->location->z);
1111 public function onCollideWithPlayer(Player $player) : void{
1122 public function isUnderwater() : bool{
1123 $block = $this->getWorld()->getBlockAt((int) floor($this->location->x), $blockY = (int) floor($y = ($this->location->y + $this->getEyeHeight())), (int) floor($this->location->z));
1125 if($block instanceof
Water){
1126 $f = ($blockY + 1) - ($block->getFluidHeightPercent() - 0.1111111);
1133 public function isInsideOfSolid() : bool{
1134 $block = $this->getWorld()->getBlockAt((int) floor($this->location->x), (int) floor($y = ($this->location->y + $this->getEyeHeight())), (int) floor($this->location->z));
1136 return $block->isSolid() && !$block->isTransparent() && $block->collidesWithBB($this->getBoundingBox());
1139 protected function move(
float $dx,
float $dy,
float $dz) : void{
1140 $this->blocksAround = null;
1142 Timings::$entityMove->startTiming();
1143 Timings::$entityMoveCollision->startTiming();
1149 if($this->keepMovement){
1150 $this->boundingBox->offset($dx, $dy, $dz);
1152 $this->ySize *= self::STEP_CLIP_MULTIPLIER;
1154 $moveBB = clone $this->boundingBox;
1156 assert(abs($dx) <= 20 && abs($dy) <= 20 && abs($dz) <= 20,
"Movement distance is excessive: dx=$dx, dy=$dy, dz=$dz");
1158 $list = $this->getWorld()->getBlockCollisionBoxes($moveBB->addCoord($dx, $dy, $dz));
1160 foreach($list as $bb){
1161 $dy = $bb->calculateYOffset($moveBB, $dy);
1164 $moveBB->offset(0, $dy, 0);
1166 $fallingFlag = ($this->onGround || ($dy != $wantedY && $wantedY < 0));
1168 foreach($list as $bb){
1169 $dx = $bb->calculateXOffset($moveBB, $dx);
1172 $moveBB->offset($dx, 0, 0);
1174 foreach($list as $bb){
1175 $dz = $bb->calculateZOffset($moveBB, $dz);
1178 $moveBB->offset(0, 0, $dz);
1180 if($this->stepHeight > 0 && $fallingFlag && ($wantedX != $dx || $wantedZ != $dz)){
1185 $dy = $this->stepHeight;
1188 $stepBB = clone $this->boundingBox;
1190 $list = $this->getWorld()->getBlockCollisionBoxes($stepBB->addCoord($dx, $dy, $dz));
1191 foreach($list as $bb){
1192 $dy = $bb->calculateYOffset($stepBB, $dy);
1195 $stepBB->offset(0, $dy, 0);
1197 foreach($list as $bb){
1198 $dx = $bb->calculateXOffset($stepBB, $dx);
1201 $stepBB->offset($dx, 0, 0);
1203 foreach($list as $bb){
1204 $dz = $bb->calculateZOffset($stepBB, $dz);
1207 $stepBB->offset(0, 0, $dz);
1210 foreach($list as $bb){
1211 $reverseDY = $bb->calculateYOffset($stepBB, $reverseDY);
1214 $stepBB->offset(0, $reverseDY, 0);
1216 if(($cx ** 2 + $cz ** 2) >= ($dx ** 2 + $dz ** 2)){
1222 $this->ySize += $dy;
1226 $this->boundingBox = $moveBB;
1228 Timings::$entityMoveCollision->stopTiming();
1230 $this->location =
new Location(
1231 ($this->boundingBox->minX + $this->boundingBox->maxX) / 2,
1232 $this->boundingBox->minY - $this->ySize,
1233 ($this->boundingBox->minZ + $this->boundingBox->maxZ) / 2,
1234 $this->location->world,
1235 $this->location->yaw,
1236 $this->location->pitch
1239 $this->getWorld()->onEntityMoved($this);
1240 $this->checkBlockIntersections();
1241 $this->checkGroundState($wantedX, $wantedY, $wantedZ, $dx, $dy, $dz);
1242 $postFallVerticalVelocity = $this->updateFallState($dy, $this->onGround);
1244 $this->motion = $this->motion->withComponents(
1245 $wantedX != $dx ? 0 :
null,
1246 $postFallVerticalVelocity ?? ($wantedY != $dy ? 0 :
null),
1247 $wantedZ != $dz ? 0 :
null
1252 Timings::$entityMove->stopTiming();
1255 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1256 $this->isCollidedVertically = $wantedY != $dy;
1257 $this->isCollidedHorizontally = ($wantedX != $dx || $wantedZ != $dz);
1258 $this->isCollided = ($this->isCollidedHorizontally || $this->isCollidedVertically);
1259 $this->onGround = ($wantedY != $dy && $wantedY < 0);
1268 $minX = (int) floor($this->boundingBox->minX + $inset);
1269 $minY = (int) floor($this->boundingBox->minY + $inset);
1270 $minZ = (int) floor($this->boundingBox->minZ + $inset);
1271 $maxX = (int) floor($this->boundingBox->maxX - $inset);
1272 $maxY = (int) floor($this->boundingBox->maxY - $inset);
1273 $maxZ = (int) floor($this->boundingBox->maxZ - $inset);
1275 $world = $this->getWorld();
1277 for($z = $minZ; $z <= $maxZ; ++$z){
1278 for($x = $minX; $x <= $maxX; ++$x){
1279 for($y = $minY; $y <= $maxY; ++$y){
1280 yield $world->getBlockAt($x, $y, $z);
1290 if($this->blocksAround === null){
1291 $this->blocksAround = [];
1294 foreach($this->getBlocksIntersected($inset) as $block){
1295 if($block->hasEntityCollision()){
1296 $this->blocksAround[] = $block;
1301 return $this->blocksAround;
1311 protected function checkBlockIntersections() : void{
1312 $this->checkBlockIntersectionsNextTick = false;
1315 foreach($this->getBlocksAroundWithEntityInsideActions() as $block){
1316 if(!$block->onEntityInside($this)){
1317 $this->blocksAround =
null;
1319 if(($v = $block->addVelocityToEntity($this)) !==
null){
1324 if(count($vectors) > 0){
1325 $vector = Vector3::sum(...$vectors);
1326 if($vector->lengthSquared() > 0){
1328 $this->motion = $this->motion->addVector($vector->normalize()->multiply($d));
1334 return $this->location->asPosition();
1337 public function getLocation() : Location{
1338 return $this->location->asLocation();
1341 public function getWorld() : World{
1342 return $this->location->getWorld();
1345 protected function setPosition(Vector3 $pos) : bool{
1350 $oldWorld = $this->getWorld();
1351 $newWorld = $pos instanceof Position ? $pos->getWorld() : $oldWorld;
1352 if($oldWorld !== $newWorld){
1353 $this->despawnFromAll();
1354 $oldWorld->removeEntity($this);
1357 $this->location = Location::fromObject(
1360 $this->location->yaw,
1361 $this->location->pitch
1364 $this->recalculateBoundingBox();
1366 $this->blocksAround =
null;
1368 if($oldWorld !== $newWorld){
1369 $newWorld->addEntity($this);
1371 $newWorld->onEntityMoved($this);
1377 public function setRotation(
float $yaw,
float $pitch) : void{
1378 Utils::checkFloatNotInfOrNaN(
"yaw", $yaw);
1379 Utils::checkFloatNotInfOrNaN(
"pitch", $pitch);
1380 $this->location->yaw = $yaw;
1381 $this->location->pitch = $pitch;
1382 $this->scheduleUpdate();
1385 protected function setPositionAndRotation(Vector3 $pos,
float $yaw,
float $pitch) : bool{
1386 if($this->setPosition($pos)){
1387 $this->setRotation($yaw, $pitch);
1395 protected function resetLastMovements() : void{
1396 $this->lastLocation = $this->location->asLocation();
1397 $this->lastMotion = clone $this->motion;
1400 public function getMotion() : Vector3{
1401 return clone $this->motion;
1404 public function setMotion(Vector3 $motion) : bool{
1405 Utils::checkVector3NotInfOrNaN($motion);
1406 if(!$this->justCreated){
1407 $ev =
new EntityMotionEvent($this, $motion);
1409 if($ev->isCancelled()){
1414 $this->motion = clone $motion;
1416 if(!$this->justCreated){
1417 $this->updateMovement();
1426 public function addMotion(
float $x,
float $y,
float $z) : void{
1427 Utils::checkFloatNotInfOrNaN(
"x", $x);
1428 Utils::checkFloatNotInfOrNaN(
"y", $y);
1429 Utils::checkFloatNotInfOrNaN(
"z", $z);
1430 $this->motion = $this->motion->add($x, $y, $z);
1433 public function isOnGround() : bool{
1434 return $this->onGround;
1441 Utils::checkVector3NotInfOrNaN($pos);
1443 $yaw = $yaw ?? $pos->yaw;
1444 $pitch = $pitch ?? $pos->pitch;
1447 Utils::checkFloatNotInfOrNaN(
"yaw", $yaw);
1449 if($pitch !==
null){
1450 Utils::checkFloatNotInfOrNaN(
"pitch", $pitch);
1453 $from = $this->location->asPosition();
1454 $to = Position::fromObject($pos, $pos instanceof Position ? $pos->getWorld() : $this->getWorld());
1455 $ev =
new EntityTeleportEvent($this, $from, $to);
1457 if($ev->isCancelled()){
1461 $pos = $ev->getTo();
1463 $this->setMotion(
new Vector3(0, 0, 0));
1464 if($this->setPositionAndRotation($pos, $yaw ?? $this->location->yaw, $pitch ?? $this->location->pitch)){
1465 $this->resetFallDistance();
1466 $this->setForceMovementUpdate();
1468 $this->updateMovement(
true);
1476 public function getId() : int{
1484 return $this->hasSpawned;
1487 abstract public static function getNetworkTypeId() : string;
1493 $player->getNetworkSession()->sendDataPacket(
AddActorPacket::create(
1496 static::getNetworkTypeId(),
1497 $this->location->asVector3(),
1499 $this->location->pitch,
1500 $this->location->yaw,
1501 $this->location->yaw,
1502 $this->location->yaw,
1503 array_map(function(
Attribute $attr) : NetworkAttribute{
1504 return new NetworkAttribute($attr->getId(), $attr->getMinValue(), $attr->getMaxValue(), $attr->getValue(), $attr->getDefaultValue(), []);
1505 }, $this->attributeMap->getAll()),
1506 $this->getAllNetworkData(),
1512 public function spawnTo(
Player $player) : void{
1513 $id = spl_object_id($player);
1517 if(!isset($this->hasSpawned[$id]) && $player->getWorld() === $this->getWorld() && $player->
hasReceivedChunk($this->location->getFloorX() >> Chunk::COORD_BIT_SIZE, $this->location->getFloorZ() >> Chunk::COORD_BIT_SIZE)){
1518 $this->hasSpawned[$id] = $player;
1520 $this->sendSpawnPacket($player);
1524 public function spawnToAll() : void{
1528 foreach($this->getWorld()->getViewersForPosition($this->location) as $player){
1529 $this->spawnTo($player);
1533 public function respawnToAll() : void{
1534 foreach($this->hasSpawned as $key => $player){
1535 unset($this->hasSpawned[$key]);
1536 $this->spawnTo($player);
1545 $id = spl_object_id($player);
1546 if(isset($this->hasSpawned[$id])){
1548 $player->getNetworkSession()->getEntityEventBroadcaster()->onEntityRemoved([$player->getNetworkSession()], $this);
1550 unset($this->hasSpawned[$id]);
1561 fn(
EntityEventBroadcaster $broadcaster, array $recipients) => $broadcaster->onEntityRemoved($recipients, $this)
1563 $this->hasSpawned = [];
1577 $this->needsDespawn = true;
1578 $this->scheduleUpdate();
1581 public function isFlaggedForDespawn() : bool{
1582 return $this->needsDespawn;
1589 return $this->closed;
1598 if($this->closeInFlight){
1603 $this->closeInFlight =
true;
1607 $this->closed =
true;
1608 $this->destroyCycles();
1609 $this->closeInFlight =
false;
1618 $this->despawnFromAll();
1619 if($this->location->isValid()){
1620 $this->getWorld()->removeEntity($this);
1631 $this->lastDamageCause = null;
1640 public function sendData(?array $targets, ?array $data =
null) : void{
1641 $targets = $targets ?? $this->hasSpawned;
1642 $data = $data ?? $this->getAllNetworkData();
1644 NetworkBroadcastUtils::broadcastEntityEvent($targets, fn(
EntityEventBroadcaster $broadcaster, array $recipients) => $broadcaster->
syncActorData($recipients, $this, $data));
1652 if($this->networkPropertiesDirty){
1653 $this->syncNetworkData($this->networkProperties);
1654 $this->networkPropertiesDirty =
false;
1656 return $this->networkProperties->getDirty();
1664 if($this->networkPropertiesDirty){
1665 $this->syncNetworkData($this->networkProperties);
1666 $this->networkPropertiesDirty =
false;
1668 return $this->networkProperties->getAll();
1671 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
1672 $properties->setByte(EntityMetadataProperties::ALWAYS_SHOW_NAMETAG, $this->alwaysShowNameTag ? 1 : 0);
1673 $properties->setFloat(EntityMetadataProperties::BOUNDING_BOX_HEIGHT, $this->size->getHeight() / $this->scale);
1674 $properties->setFloat(EntityMetadataProperties::BOUNDING_BOX_WIDTH, $this->size->getWidth() / $this->scale);
1675 $properties->setFloat(EntityMetadataProperties::SCALE, $this->scale);
1676 $properties->setLong(EntityMetadataProperties::LEAD_HOLDER_EID, -1);
1677 $properties->setLong(EntityMetadataProperties::OWNER_EID, $this->ownerId ?? -1);
1678 $properties->setLong(EntityMetadataProperties::TARGET_EID, $this->targetId ?? 0);
1679 $properties->setString(EntityMetadataProperties::NAMETAG, $this->nameTag);
1680 $properties->setString(EntityMetadataProperties::SCORE_TAG, $this->scoreTag);
1681 $properties->setByte(EntityMetadataProperties::COLOR, 0);
1683 $properties->setGenericFlag(EntityMetadataFlags::AFFECTED_BY_GRAVITY, $this->gravityEnabled);
1684 $properties->setGenericFlag(EntityMetadataFlags::CAN_CLIMB, $this->canClimb);
1685 $properties->setGenericFlag(EntityMetadataFlags::CAN_SHOW_NAMETAG, $this->nameTagVisible);
1686 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION,
true);
1687 $properties->setGenericFlag(EntityMetadataFlags::NO_AI, $this->noClientPredictions);
1688 $properties->setGenericFlag(EntityMetadataFlags::INVISIBLE, $this->invisible);
1689 $properties->setGenericFlag(EntityMetadataFlags::SILENT, $this->silent);
1690 $properties->setGenericFlag(EntityMetadataFlags::ONFIRE, $this->isOnFire());
1691 $properties->setGenericFlag(EntityMetadataFlags::WALLCLIMBING, $this->canClimbWalls);
1707 $this->getWorld()->addSound($this->location->asVector3(), $sound, $targets ?? $this->getViewers());
1711 public function __destruct(){
1715 public function __toString(){
1716 return (
new \ReflectionClass($this))->getShortName() .
"(" . $this->getId() .
")";