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++;
106 protected array $hasSpawned = [];
115 protected ?array $blocksAround =
null;
121 protected bool $forceMovementUpdate =
false;
122 private bool $checkBlockIntersectionsNextTick =
true;
125 public bool $onGround =
false;
129 private float $health = 20.0;
130 private int $maxHealth = 20;
132 protected float $ySize = 0.0;
133 protected float $stepHeight = 0.0;
134 public bool $keepMovement =
false;
136 public float $fallDistance = 0.0;
137 public int $ticksLived = 0;
138 public int $lastUpdate;
139 protected int $fireTicks = 0;
141 private bool $savedWithChunk =
true;
143 public bool $isCollided =
false;
144 public bool $isCollidedHorizontally =
false;
145 public bool $isCollidedVertically =
false;
147 public int $noDamageTicks = 0;
148 protected bool $justCreated =
true;
152 protected float $gravity;
153 protected float $drag;
154 protected bool $gravityEnabled =
true;
158 protected bool $closed =
false;
159 private bool $closeInFlight =
false;
160 private bool $needsDespawn =
false;
164 protected bool $networkPropertiesDirty =
false;
166 protected string $nameTag =
"";
167 protected bool $nameTagVisible =
true;
168 protected bool $alwaysShowNameTag =
false;
169 protected string $scoreTag =
"";
170 protected float $scale = 1.0;
172 protected bool $canClimb =
false;
173 protected bool $canClimbWalls =
false;
174 protected bool $noClientPredictions =
false;
175 protected bool $invisible =
false;
176 protected bool $silent =
false;
178 protected ?
int $ownerId =
null;
179 protected ?
int $targetId =
null;
181 private bool $constructorCalled =
false;
184 if($this->constructorCalled){
185 throw new \LogicException(
"Attempted to call constructor for an Entity multiple times");
187 $this->constructorCalled =
true;
188 Utils::checkLocationNotInfOrNaN($location);
190 $this->timings = Timings::getEntityTimings($this);
192 $this->size = $this->getInitialSizeInfo();
193 $this->drag = $this->getInitialDragMultiplier();
194 $this->gravity = $this->getInitialGravity();
196 $this->
id = self::nextRuntimeId();
201 $this->boundingBox =
new AxisAlignedBB(0, 0, 0, 0, 0, 0);
202 $this->recalculateBoundingBox();
207 $this->motion = Vector3::zero();
210 $this->resetLastMovements();
212 $this->networkProperties =
new EntityMetadataCollection();
214 $this->attributeMap =
new AttributeMap();
215 $this->addAttributes();
217 $this->initEntity($nbt ??
new CompoundTag());
219 $this->getWorld()->addEntity($this);
221 $this->lastUpdate = $this->
server->getTick();
223 $this->scheduleUpdate();
226 abstract protected function getInitialSizeInfo() : EntitySizeInfo;
243 public function getNameTag() : string{
244 return $this->nameTag;
247 public function isNameTagVisible() : bool{
248 return $this->nameTagVisible;
251 public function isNameTagAlwaysVisible() : bool{
252 return $this->alwaysShowNameTag;
263 public function setNameTag(
string $name) : void{
264 $this->nameTag = $name;
265 $this->networkPropertiesDirty =
true;
268 public function setNameTagVisible(
bool $value =
true) : void{
269 $this->nameTagVisible = $value;
270 $this->networkPropertiesDirty =
true;
273 public function setNameTagAlwaysVisible(
bool $value =
true) : void{
274 $this->alwaysShowNameTag = $value;
275 $this->networkPropertiesDirty =
true;
278 public function getScoreTag() : ?string{
279 return $this->scoreTag;
282 public function setScoreTag(
string $score) : void{
283 $this->scoreTag = $score;
284 $this->networkPropertiesDirty =
true;
287 public function getScale() : float{
291 public function setScale(
float $value) : void{
293 throw new \InvalidArgumentException(
"Scale must be greater than 0");
295 $this->scale = $value;
296 $this->setSize($this->getInitialSizeInfo()->scale($value));
299 public function getBoundingBox() : AxisAlignedBB{
300 return $this->boundingBox;
303 protected function recalculateBoundingBox() : void{
304 $halfWidth = $this->size->getWidth() / 2;
306 $this->boundingBox =
new AxisAlignedBB(
307 $this->location->x - $halfWidth,
308 $this->location->y + $this->ySize,
309 $this->location->z - $halfWidth,
310 $this->location->x + $halfWidth,
311 $this->location->y + $this->size->getHeight() + $this->ySize,
312 $this->location->z + $halfWidth
316 public function getSize() : EntitySizeInfo{
320 protected function setSize(EntitySizeInfo $size) : void{
322 $this->recalculateBoundingBox();
323 $this->networkPropertiesDirty =
true;
331 return $this->noClientPredictions;
343 $this->noClientPredictions = $value;
344 $this->networkPropertiesDirty =
true;
347 public function isInvisible() : bool{
348 return $this->invisible;
351 public function setInvisible(
bool $value =
true) : void{
352 $this->invisible = $value;
353 $this->networkPropertiesDirty =
true;
356 public function isSilent() : bool{
357 return $this->silent;
360 public function setSilent(
bool $value =
true) : void{
361 $this->silent = $value;
362 $this->networkPropertiesDirty =
true;
369 return $this->canClimb;
376 $this->canClimb = $value;
377 $this->networkPropertiesDirty =
true;
384 return $this->canClimbWalls;
391 $this->canClimbWalls = $value;
392 $this->networkPropertiesDirty =
true;
399 return $this->ownerId;
406 return $this->ownerId !== null ? $this->
server->getWorldManager()->findEntity($this->ownerId) : null;
416 $this->ownerId =
null;
417 }elseif($owner->closed){
418 throw new \InvalidArgumentException(
"Supplied owning entity is garbage and cannot be used");
420 $this->ownerId = $owner->getId();
422 $this->networkPropertiesDirty =
true;
429 return $this->targetId;
437 return $this->targetId !== null ? $this->
server->getWorldManager()->findEntity($this->targetId) : null;
446 if($target === null){
447 $this->targetId =
null;
448 }elseif($target->closed){
449 throw new \InvalidArgumentException(
"Supplied target entity is garbage and cannot be used");
451 $this->targetId = $target->getId();
453 $this->networkPropertiesDirty =
true;
460 return $this->savedWithChunk;
468 $this->savedWithChunk = $value;
473 ->setTag(self::TAG_POS, new
ListTag([
478 ->setTag(self::TAG_MOTION, new
ListTag([
483 ->setTag(self::TAG_ROTATION, new
ListTag([
485 new
FloatTag($this->location->pitch)
488 if(!($this instanceof
Player)){
489 EntityFactory::getInstance()->injectSaveId(get_class($this), $nbt);
491 if($this->getNameTag() !==
""){
492 $nbt->setString(self::TAG_CUSTOM_NAME, $this->getNameTag());
493 $nbt->setByte(self::TAG_CUSTOM_NAME_VISIBLE, $this->isNameTagVisible() ? 1 : 0);
497 $nbt->
setFloat(self::TAG_FALL_DISTANCE, $this->fallDistance);
498 $nbt->setShort(self::TAG_FIRE, $this->fireTicks);
499 $nbt->setByte(self::TAG_ON_GROUND, $this->onGround ? 1 : 0);
501 $nbt->setLong(VersionInfo::TAG_WORLD_DATA_VERSION, VersionInfo::WORLD_DATA_VERSION);
506 protected function initEntity(CompoundTag $nbt) : void{
507 $this->fireTicks = $nbt->getShort(self::TAG_FIRE, 0);
509 $this->onGround = $nbt->getByte(self::TAG_ON_GROUND, 0) !== 0;
511 $this->fallDistance = $nbt->getFloat(self::TAG_FALL_DISTANCE, 0.0);
513 if(($customNameTag = $nbt->getTag(self::TAG_CUSTOM_NAME)) instanceof StringTag){
514 $this->setNameTag($customNameTag->getValue());
516 if(($customNameVisibleTag = $nbt->getTag(self::TAG_CUSTOM_NAME_VISIBLE)) instanceof StringTag){
518 $this->setNameTagVisible($customNameVisibleTag->getValue() !==
"");
520 $this->setNameTagVisible($nbt->getByte(self::TAG_CUSTOM_NAME_VISIBLE, 1) !== 0);
525 protected function addAttributes() : void{
529 public function attack(EntityDamageEvent $source) : void{
530 if($this->isFireProof() && (
531 $source->getCause() === EntityDamageEvent::CAUSE_FIRE ||
532 $source->getCause() === EntityDamageEvent::CAUSE_FIRE_TICK ||
533 $source->getCause() === EntityDamageEvent::CAUSE_LAVA
539 if($source->isCancelled()){
543 $this->setLastDamageCause($source);
545 $this->setHealth($this->getHealth() - $source->getFinalDamage());
548 public function heal(EntityRegainHealthEvent $source) : void{
550 if($source->isCancelled()){
554 $this->setHealth($this->getHealth() + $source->getAmount());
557 public function kill() : void{
558 if($this->isAlive()){
561 $this->scheduleUpdate();
575 protected function onDeathUpdate(int $tickDiff) : bool{
579 public function isAlive() : bool{
580 return $this->health > 0;
583 public function getHealth() : float{
584 return $this->health;
591 if($amount == $this->health){
596 if($this->isAlive()){
597 if(!$this->justCreated){
603 }elseif($amount <= $this->getMaxHealth() || $amount < $this->health){
604 $this->health = $amount;
606 $this->health = $this->getMaxHealth();
610 public function getMaxHealth() : int{
611 return $this->maxHealth;
614 public function setMaxHealth(
int $amount) : void{
615 $this->maxHealth = $amount;
618 public function setLastDamageCause(EntityDamageEvent $type) : void{
619 $this->lastDamageCause = $type;
622 public function getLastDamageCause() : ?EntityDamageEvent{
623 return $this->lastDamageCause;
626 public function getAttributeMap() : AttributeMap{
627 return $this->attributeMap;
630 public function getNetworkProperties() : EntityMetadataCollection{
631 return $this->networkProperties;
634 protected function entityBaseTick(
int $tickDiff = 1) : bool{
637 if($this->justCreated){
638 $this->justCreated =
false;
639 if(!$this->isAlive()){
644 $changedProperties = $this->getDirtyNetworkData();
645 if(count($changedProperties) > 0){
646 $this->sendData(
null, $changedProperties);
647 $this->networkProperties->clearDirtyProperties();
652 if($this->checkBlockIntersectionsNextTick){
653 $this->checkBlockIntersections();
655 $this->checkBlockIntersectionsNextTick =
true;
657 if($this->location->y <= World::Y_MIN - 16 && $this->isAlive()){
658 $ev =
new EntityDamageEvent($this, EntityDamageEvent::CAUSE_VOID, 10);
663 if($this->isOnFire() && $this->doOnFireTick($tickDiff)){
667 if($this->noDamageTicks > 0){
668 $this->noDamageTicks -= $tickDiff;
669 if($this->noDamageTicks < 0){
670 $this->noDamageTicks = 0;
674 $this->ticksLived += $tickDiff;
679 public function isOnFire() : bool{
680 return $this->fireTicks > 0;
683 public function setOnFire(
int $seconds) : void{
684 $ticks = $seconds * 20;
685 if($ticks > $this->getFireTicks()){
686 $this->setFireTicks($ticks);
688 $this->networkPropertiesDirty =
true;
691 public function getFireTicks() : int{
692 return $this->fireTicks;
699 if($fireTicks < 0 || $fireTicks > 0x7fff){
700 throw new \InvalidArgumentException(
"Fire ticks must be in range 0 ... " . 0x7fff .
", got $fireTicks");
702 if(!$this->isFireProof()){
703 $this->fireTicks = $fireTicks;
704 $this->networkPropertiesDirty =
true;
708 public function extinguish() : void{
709 $this->fireTicks = 0;
710 $this->networkPropertiesDirty =
true;
713 public function isFireProof() : bool{
717 protected function doOnFireTick(
int $tickDiff = 1) : bool{
718 if($this->isFireProof() && $this->isOnFire()){
723 $this->fireTicks -= $tickDiff;
725 if(($this->fireTicks % 20 === 0) || $tickDiff > 20){
726 $this->dealFireDamage();
729 if(!$this->isOnFire()){
746 public function canCollideWith(
Entity $entity) : bool{
747 return !$this->justCreated && $entity !== $this;
750 public function canBeCollidedWith() : bool{
751 return $this->isAlive();
754 protected function updateMovement(
bool $teleport =
false) : void{
755 $diffPosition = $this->location->distanceSquared($this->lastLocation);
756 $diffRotation = ($this->location->yaw - $this->lastLocation->yaw) ** 2 + ($this->location->pitch - $this->lastLocation->pitch) ** 2;
758 $diffMotion = $this->motion->subtractVector($this->lastMotion)->lengthSquared();
760 $still = $this->motion->lengthSquared() == 0.0;
761 $wasStill = $this->lastMotion->lengthSquared() == 0.0;
762 if($wasStill !== $still){
764 $this->setNoClientPredictions($still);
767 if($teleport || $diffPosition > 0.0001 || $diffRotation > 1.0 || (!$wasStill && $still)){
768 $this->lastLocation = $this->location->asLocation();
770 $this->broadcastMovement($teleport);
773 if($diffMotion > 0.0025 || $wasStill !== $still){
774 $this->lastMotion = clone $this->motion;
776 $this->broadcastMotion();
780 public function getOffsetPosition(Vector3 $vector3) : Vector3{
784 protected function broadcastMovement(
bool $teleport =
false) : void{
785 NetworkBroadcastUtils::broadcastPackets($this->hasSpawned, [MoveActorAbsolutePacket::create(
787 $this->getOffsetPosition($this->location),
788 $this->location->pitch,
789 $this->location->yaw,
790 $this->location->yaw,
797 ($this->onGround ? MoveActorAbsolutePacket::FLAG_GROUND : 0)
802 protected function broadcastMotion() : void{
803 NetworkBroadcastUtils::broadcastPackets($this->hasSpawned, [SetActorMotionPacket::create($this->
id, $this->getMotion(), tick: 0)]);
806 public function getGravity() : float{
807 return $this->gravity;
810 public function setGravity(
float $gravity) : void{
811 Utils::checkFloatNotInfOrNaN(
"gravity", $gravity);
812 $this->gravity = $gravity;
815 public function hasGravity() : bool{
816 return $this->gravityEnabled;
819 public function setHasGravity(
bool $v =
true) : void{
820 $this->gravityEnabled = $v;
823 protected function applyDragBeforeGravity() : bool{
827 protected function tryChangeMovement() : void{
828 $friction = 1 - $this->drag;
830 $mY = $this->motion->y;
832 if($this->applyDragBeforeGravity()){
836 if($this->gravityEnabled){
837 $mY -= $this->gravity;
840 if(!$this->applyDragBeforeGravity()){
845 $friction *= $this->getWorld()->getBlockAt((
int) floor($this->location->x), (
int) floor($this->location->y - 1), (
int) floor($this->location->z))->getFrictionFactor();
848 $this->motion =
new Vector3($this->motion->x * $friction, $mY, $this->motion->z * $friction);
851 protected function checkObstruction(
float $x,
float $y,
float $z) : bool{
852 $world = $this->getWorld();
853 if(count($world->getBlockCollisionBoxes($this->boundingBox)) === 0){
857 $floorX = (
int) floor($x);
858 $floorY = (int) floor($y);
859 $floorZ = (int) floor($z);
861 $diffX = $x - $floorX;
862 $diffY = $y - $floorY;
863 $diffZ = $z - $floorZ;
865 if($world->getBlockAt($floorX, $floorY, $floorZ)->isSolid()){
866 $westNonSolid = !$world->getBlockAt($floorX - 1, $floorY, $floorZ)->isSolid();
867 $eastNonSolid = !$world->getBlockAt($floorX + 1, $floorY, $floorZ)->isSolid();
868 $downNonSolid = !$world->getBlockAt($floorX, $floorY - 1, $floorZ)->isSolid();
869 $upNonSolid = !$world->getBlockAt($floorX, $floorY + 1, $floorZ)->isSolid();
870 $northNonSolid = !$world->getBlockAt($floorX, $floorY, $floorZ - 1)->isSolid();
871 $southNonSolid = !$world->getBlockAt($floorX, $floorY, $floorZ + 1)->isSolid();
878 $direction = Facing::WEST;
881 if($eastNonSolid && 1 - $diffX < $limit){
883 $direction = Facing::EAST;
886 if($downNonSolid && $diffY < $limit){
888 $direction = Facing::DOWN;
891 if($upNonSolid && 1 - $diffY < $limit){
893 $direction = Facing::UP;
896 if($northNonSolid && $diffZ < $limit){
898 $direction = Facing::NORTH;
901 if($southNonSolid && 1 - $diffZ < $limit){
902 $direction = Facing::SOUTH;
905 if($direction === -1){
909 $force = lcg_value() * 0.2 + 0.1;
911 $this->motion = match($direction){
912 Facing::WEST => $this->motion->withComponents(-$force,
null,
null),
913 Facing::EAST => $this->motion->withComponents($force,
null,
null),
914 Facing::DOWN => $this->motion->withComponents(
null, -$force,
null),
915 Facing::UP => $this->motion->withComponents(
null, $force,
null),
916 Facing::NORTH => $this->motion->withComponents(
null,
null, -$force),
917 Facing::SOUTH => $this->motion->withComponents(
null,
null, $force),
925 public function getHorizontalFacing() : int{
926 $angle = fmod($this->location->yaw, 360);
931 if((0 <= $angle && $angle < 45) || (315 <= $angle && $angle < 360)){
932 return Facing::SOUTH;
934 if(45 <= $angle && $angle < 135){
937 if(135 <= $angle && $angle < 225){
938 return Facing::NORTH;
944 public function getDirectionVector() : Vector3{
945 $y = -sin(deg2rad($this->location->pitch));
946 $xz = cos(deg2rad($this->location->pitch));
947 $x = -$xz * sin(deg2rad($this->location->yaw));
948 $z = $xz * cos(deg2rad($this->location->yaw));
950 return (
new Vector3($x, $y, $z))->normalize();
953 public function getDirectionPlane() : Vector2{
954 return (new Vector2(-cos(deg2rad($this->location->yaw) - M_PI_2), -sin(deg2rad($this->location->yaw) - M_PI_2)))->normalize();
965 public function onUpdate(
int $currentTick) : bool{
970 $tickDiff = $currentTick - $this->lastUpdate;
972 if(!$this->justCreated){
973 $this->
server->getLogger()->debug(
"Expected tick difference of at least 1, got $tickDiff for " . get_class($this));
979 $this->lastUpdate = $currentTick;
981 if($this->justCreated){
982 $this->onFirstUpdate($currentTick);
985 if(!$this->isAlive()){
986 if($this->onDeathUpdate($tickDiff)){
987 $this->flagForDespawn();
993 $this->timings->startTiming();
995 if($this->hasMovementUpdate()){
996 $this->tryChangeMovement();
998 $this->motion = $this->motion->withComponents(
999 abs($this->motion->x) <= self::MOTION_THRESHOLD ? 0 :
null,
1000 abs($this->motion->y) <= self::MOTION_THRESHOLD ? 0 :
null,
1001 abs($this->motion->z) <= self::MOTION_THRESHOLD ? 0 :
null
1004 if($this->motion->x != 0 || $this->motion->y != 0 || $this->motion->z != 0){
1005 $this->move($this->motion->x, $this->motion->y, $this->motion->z);
1008 $this->forceMovementUpdate =
false;
1011 $this->updateMovement();
1013 Timings::$entityBaseTick->startTiming();
1014 $hasUpdate = $this->entityBaseTick($tickDiff);
1015 Timings::$entityBaseTick->stopTiming();
1017 $this->timings->stopTiming();
1019 return ($hasUpdate || $this->hasMovementUpdate());
1022 final public function scheduleUpdate() : void{
1024 throw new \LogicException(
"Cannot schedule update on garbage entity " . get_class($this));
1026 $this->getWorld()->updateEntities[$this->id] = $this;
1029 public function onNearbyBlockChange() : void{
1030 $this->setForceMovementUpdate();
1031 $this->scheduleUpdate();
1039 $this->scheduleUpdate();
1047 $this->forceMovementUpdate = $value;
1049 $this->blocksAround =
null;
1057 $this->forceMovementUpdate ||
1058 $this->motion->x != 0 ||
1059 $this->motion->y != 0 ||
1060 $this->motion->z != 0 ||
1065 public function getFallDistance() : float{ return $this->fallDistance; }
1067 public function setFallDistance(
float $fallDistance) : void{
1068 $this->fallDistance = $fallDistance;
1071 public function resetFallDistance() : void{
1072 $this->fallDistance = 0.0;
1075 protected function updateFallState(
float $distanceThisTick,
bool $onGround) : ?float{
1076 if($distanceThisTick < $this->fallDistance){
1079 $this->fallDistance -= $distanceThisTick;
1083 $this->fallDistance = 0;
1085 if($onGround && $this->fallDistance > 0){
1086 $newVerticalVelocity = $this->onHitGround();
1087 $this->resetFallDistance();
1088 return $newVerticalVelocity;
1100 public function getEyeHeight() : float{
1101 return $this->size->getEyeHeight();
1104 public function getEyePos() : Vector3{
1105 return new Vector3($this->location->x, $this->location->y + $this->getEyeHeight(), $this->location->z);
1108 public function onCollideWithPlayer(Player $player) : void{
1119 public function isUnderwater() : bool{
1120 $block = $this->getWorld()->getBlockAt((int) floor($this->location->x), $blockY = (int) floor($y = ($this->location->y + $this->getEyeHeight())), (int) floor($this->location->z));
1122 if($block instanceof
Water){
1123 $f = ($blockY + 1) - ($block->getFluidHeightPercent() - 0.1111111);
1130 public function isInsideOfSolid() : bool{
1131 $block = $this->getWorld()->getBlockAt((int) floor($this->location->x), (int) floor($y = ($this->location->y + $this->getEyeHeight())), (int) floor($this->location->z));
1133 return $block->isSolid() && !$block->isTransparent() && $block->collidesWithBB($this->getBoundingBox());
1136 protected function move(
float $dx,
float $dy,
float $dz) : void{
1137 $this->blocksAround = null;
1139 Timings::$entityMove->startTiming();
1140 Timings::$entityMoveCollision->startTiming();
1146 if($this->keepMovement){
1147 $this->boundingBox->offset($dx, $dy, $dz);
1149 $this->ySize *= self::STEP_CLIP_MULTIPLIER;
1151 $moveBB = clone $this->boundingBox;
1153 assert(abs($dx) <= 20 && abs($dy) <= 20 && abs($dz) <= 20,
"Movement distance is excessive: dx=$dx, dy=$dy, dz=$dz");
1155 $list = $this->getWorld()->getBlockCollisionBoxes($moveBB->addCoord($dx, $dy, $dz));
1157 foreach($list as $bb){
1158 $dy = $bb->calculateYOffset($moveBB, $dy);
1161 $moveBB->offset(0, $dy, 0);
1163 $fallingFlag = ($this->onGround || ($dy != $wantedY && $wantedY < 0));
1165 foreach($list as $bb){
1166 $dx = $bb->calculateXOffset($moveBB, $dx);
1169 $moveBB->offset($dx, 0, 0);
1171 foreach($list as $bb){
1172 $dz = $bb->calculateZOffset($moveBB, $dz);
1175 $moveBB->offset(0, 0, $dz);
1177 if($this->stepHeight > 0 && $fallingFlag && ($wantedX != $dx || $wantedZ != $dz)){
1182 $dy = $this->stepHeight;
1185 $stepBB = clone $this->boundingBox;
1187 $list = $this->getWorld()->getBlockCollisionBoxes($stepBB->addCoord($dx, $dy, $dz));
1188 foreach($list as $bb){
1189 $dy = $bb->calculateYOffset($stepBB, $dy);
1192 $stepBB->offset(0, $dy, 0);
1194 foreach($list as $bb){
1195 $dx = $bb->calculateXOffset($stepBB, $dx);
1198 $stepBB->offset($dx, 0, 0);
1200 foreach($list as $bb){
1201 $dz = $bb->calculateZOffset($stepBB, $dz);
1204 $stepBB->offset(0, 0, $dz);
1207 foreach($list as $bb){
1208 $reverseDY = $bb->calculateYOffset($stepBB, $reverseDY);
1211 $stepBB->offset(0, $reverseDY, 0);
1213 if(($cx ** 2 + $cz ** 2) >= ($dx ** 2 + $dz ** 2)){
1219 $this->ySize += $dy;
1223 $this->boundingBox = $moveBB;
1225 Timings::$entityMoveCollision->stopTiming();
1227 $this->location =
new Location(
1228 ($this->boundingBox->minX + $this->boundingBox->maxX) / 2,
1229 $this->boundingBox->minY - $this->ySize,
1230 ($this->boundingBox->minZ + $this->boundingBox->maxZ) / 2,
1231 $this->location->world,
1232 $this->location->yaw,
1233 $this->location->pitch
1236 $this->getWorld()->onEntityMoved($this);
1237 $this->checkBlockIntersections();
1238 $this->checkGroundState($wantedX, $wantedY, $wantedZ, $dx, $dy, $dz);
1239 $postFallVerticalVelocity = $this->updateFallState($dy, $this->onGround);
1241 $this->motion = $this->motion->withComponents(
1242 $wantedX != $dx ? 0 :
null,
1243 $postFallVerticalVelocity ?? ($wantedY != $dy ? 0 :
null),
1244 $wantedZ != $dz ? 0 :
null
1249 Timings::$entityMove->stopTiming();
1252 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1253 $this->isCollidedVertically = $wantedY != $dy;
1254 $this->isCollidedHorizontally = ($wantedX != $dx || $wantedZ != $dz);
1255 $this->isCollided = ($this->isCollidedHorizontally || $this->isCollidedVertically);
1256 $this->onGround = ($wantedY != $dy && $wantedY < 0);
1265 $minX = (int) floor($this->boundingBox->minX + $inset);
1266 $minY = (int) floor($this->boundingBox->minY + $inset);
1267 $minZ = (int) floor($this->boundingBox->minZ + $inset);
1268 $maxX = (int) floor($this->boundingBox->maxX - $inset);
1269 $maxY = (int) floor($this->boundingBox->maxY - $inset);
1270 $maxZ = (int) floor($this->boundingBox->maxZ - $inset);
1272 $world = $this->getWorld();
1274 for($z = $minZ; $z <= $maxZ; ++$z){
1275 for($x = $minX; $x <= $maxX; ++$x){
1276 for($y = $minY; $y <= $maxY; ++$y){
1277 yield $world->getBlockAt($x, $y, $z);
1287 if($this->blocksAround === null){
1288 $this->blocksAround = [];
1291 foreach($this->getBlocksIntersected($inset) as $block){
1292 if($block->hasEntityCollision()){
1293 $this->blocksAround[] = $block;
1298 return $this->blocksAround;
1308 protected function checkBlockIntersections() : void{
1309 $this->checkBlockIntersectionsNextTick = false;
1312 foreach($this->getBlocksAroundWithEntityInsideActions() as $block){
1313 if(!$block->onEntityInside($this)){
1314 $this->blocksAround =
null;
1316 if(($v = $block->addVelocityToEntity($this)) !==
null){
1321 if(count($vectors) > 0){
1322 $vector = Vector3::sum(...$vectors);
1323 if($vector->lengthSquared() > 0){
1325 $this->motion = $this->motion->addVector($vector->normalize()->multiply($d));
1331 return $this->location->asPosition();
1334 public function getLocation() : Location{
1335 return $this->location->asLocation();
1338 public function getWorld() : World{
1339 return $this->location->getWorld();
1342 protected function setPosition(Vector3 $pos) : bool{
1347 $oldWorld = $this->getWorld();
1348 $newWorld = $pos instanceof Position ? $pos->getWorld() : $oldWorld;
1349 if($oldWorld !== $newWorld){
1350 $this->despawnFromAll();
1351 $oldWorld->removeEntity($this);
1354 $this->location = Location::fromObject(
1357 $this->location->yaw,
1358 $this->location->pitch
1361 $this->recalculateBoundingBox();
1363 $this->blocksAround =
null;
1365 if($oldWorld !== $newWorld){
1366 $newWorld->addEntity($this);
1368 $newWorld->onEntityMoved($this);
1374 public function setRotation(
float $yaw,
float $pitch) : void{
1375 Utils::checkFloatNotInfOrNaN(
"yaw", $yaw);
1376 Utils::checkFloatNotInfOrNaN(
"pitch", $pitch);
1377 $this->location->yaw = $yaw;
1378 $this->location->pitch = $pitch;
1379 $this->scheduleUpdate();
1382 protected function setPositionAndRotation(Vector3 $pos,
float $yaw,
float $pitch) : bool{
1383 if($this->setPosition($pos)){
1384 $this->setRotation($yaw, $pitch);
1392 protected function resetLastMovements() : void{
1393 $this->lastLocation = $this->location->asLocation();
1394 $this->lastMotion = clone $this->motion;
1397 public function getMotion() : Vector3{
1398 return clone $this->motion;
1401 public function setMotion(Vector3 $motion) : bool{
1402 Utils::checkVector3NotInfOrNaN($motion);
1403 if(!$this->justCreated){
1404 $ev =
new EntityMotionEvent($this, $motion);
1406 if($ev->isCancelled()){
1411 $this->motion = clone $motion;
1413 if(!$this->justCreated){
1414 $this->updateMovement();
1423 public function addMotion(
float $x,
float $y,
float $z) : void{
1424 Utils::checkFloatNotInfOrNaN(
"x", $x);
1425 Utils::checkFloatNotInfOrNaN(
"y", $y);
1426 Utils::checkFloatNotInfOrNaN(
"z", $z);
1427 $this->motion = $this->motion->add($x, $y, $z);
1430 public function isOnGround() : bool{
1431 return $this->onGround;
1438 Utils::checkVector3NotInfOrNaN($pos);
1440 $yaw = $yaw ?? $pos->yaw;
1441 $pitch = $pitch ?? $pos->pitch;
1444 Utils::checkFloatNotInfOrNaN(
"yaw", $yaw);
1446 if($pitch !==
null){
1447 Utils::checkFloatNotInfOrNaN(
"pitch", $pitch);
1450 $from = $this->location->asPosition();
1451 $to = Position::fromObject($pos, $pos instanceof Position ? $pos->getWorld() : $this->getWorld());
1452 $ev =
new EntityTeleportEvent($this, $from, $to);
1454 if($ev->isCancelled()){
1458 $pos = $ev->getTo();
1460 $this->setMotion(
new Vector3(0, 0, 0));
1461 if($this->setPositionAndRotation($pos, $yaw ?? $this->location->yaw, $pitch ?? $this->location->pitch)){
1462 $this->resetFallDistance();
1463 $this->setForceMovementUpdate();
1465 $this->updateMovement(
true);
1473 public function getId() : int{
1481 return $this->hasSpawned;
1484 abstract public static function getNetworkTypeId() : string;
1490 $player->getNetworkSession()->sendDataPacket(
AddActorPacket::create(
1493 static::getNetworkTypeId(),
1494 $this->location->asVector3(),
1496 $this->location->pitch,
1497 $this->location->yaw,
1498 $this->location->yaw,
1499 $this->location->yaw,
1500 array_map(function(
Attribute $attr) : NetworkAttribute{
1501 return new NetworkAttribute($attr->getId(), $attr->getMinValue(), $attr->getMaxValue(), $attr->getValue(), $attr->getDefaultValue(), []);
1502 }, $this->attributeMap->getAll()),
1503 $this->getAllNetworkData(),
1509 public function spawnTo(
Player $player) : void{
1510 $id = spl_object_id($player);
1514 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)){
1515 $this->hasSpawned[$id] = $player;
1517 $this->sendSpawnPacket($player);
1521 public function spawnToAll() : void{
1525 foreach($this->getWorld()->getViewersForPosition($this->location) as $player){
1526 $this->spawnTo($player);
1530 public function respawnToAll() : void{
1531 foreach($this->hasSpawned as $key => $player){
1532 unset($this->hasSpawned[$key]);
1533 $this->spawnTo($player);
1542 $id = spl_object_id($player);
1543 if(isset($this->hasSpawned[$id])){
1545 $player->getNetworkSession()->getEntityEventBroadcaster()->onEntityRemoved([$player->getNetworkSession()], $this);
1547 unset($this->hasSpawned[$id]);
1558 fn(
EntityEventBroadcaster $broadcaster, array $recipients) => $broadcaster->onEntityRemoved($recipients, $this)
1560 $this->hasSpawned = [];
1567 $this->needsDespawn = true;
1568 $this->scheduleUpdate();
1571 public function isFlaggedForDespawn() : bool{
1572 return $this->needsDespawn;
1579 return $this->closed;
1588 if($this->closeInFlight){
1593 $this->closeInFlight =
true;
1597 $this->closed =
true;
1598 $this->destroyCycles();
1599 $this->closeInFlight =
false;
1608 $this->despawnFromAll();
1609 if($this->location->isValid()){
1610 $this->getWorld()->removeEntity($this);
1621 $this->lastDamageCause = null;
1630 public function sendData(?array $targets, ?array $data =
null) : void{
1631 $targets = $targets ?? $this->hasSpawned;
1632 $data = $data ?? $this->getAllNetworkData();
1634 NetworkBroadcastUtils::broadcastEntityEvent($targets, fn(
EntityEventBroadcaster $broadcaster, array $recipients) => $broadcaster->
syncActorData($recipients, $this, $data));
1642 if($this->networkPropertiesDirty){
1643 $this->syncNetworkData($this->networkProperties);
1644 $this->networkPropertiesDirty =
false;
1646 return $this->networkProperties->getDirty();
1654 if($this->networkPropertiesDirty){
1655 $this->syncNetworkData($this->networkProperties);
1656 $this->networkPropertiesDirty =
false;
1658 return $this->networkProperties->getAll();
1661 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
1662 $properties->setByte(EntityMetadataProperties::ALWAYS_SHOW_NAMETAG, $this->alwaysShowNameTag ? 1 : 0);
1663 $properties->setFloat(EntityMetadataProperties::BOUNDING_BOX_HEIGHT, $this->size->getHeight() / $this->scale);
1664 $properties->setFloat(EntityMetadataProperties::BOUNDING_BOX_WIDTH, $this->size->getWidth() / $this->scale);
1665 $properties->setFloat(EntityMetadataProperties::SCALE, $this->scale);
1666 $properties->setLong(EntityMetadataProperties::LEAD_HOLDER_EID, -1);
1667 $properties->setLong(EntityMetadataProperties::OWNER_EID, $this->ownerId ?? -1);
1668 $properties->setLong(EntityMetadataProperties::TARGET_EID, $this->targetId ?? 0);
1669 $properties->setString(EntityMetadataProperties::NAMETAG, $this->nameTag);
1670 $properties->setString(EntityMetadataProperties::SCORE_TAG, $this->scoreTag);
1671 $properties->setByte(EntityMetadataProperties::COLOR, 0);
1673 $properties->setGenericFlag(EntityMetadataFlags::AFFECTED_BY_GRAVITY, $this->gravityEnabled);
1674 $properties->setGenericFlag(EntityMetadataFlags::CAN_CLIMB, $this->canClimb);
1675 $properties->setGenericFlag(EntityMetadataFlags::CAN_SHOW_NAMETAG, $this->nameTagVisible);
1676 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION,
true);
1677 $properties->setGenericFlag(EntityMetadataFlags::NO_AI, $this->noClientPredictions);
1678 $properties->setGenericFlag(EntityMetadataFlags::INVISIBLE, $this->invisible);
1679 $properties->setGenericFlag(EntityMetadataFlags::SILENT, $this->silent);
1680 $properties->setGenericFlag(EntityMetadataFlags::ONFIRE, $this->isOnFire());
1681 $properties->setGenericFlag(EntityMetadataFlags::WALLCLIMBING, $this->canClimbWalls);
1697 $this->getWorld()->addSound($this->location->asVector3(), $sound, $targets ?? $this->getViewers());
1701 public function __destruct(){
1705 public function __toString(){
1706 return (
new \ReflectionClass($this))->getShortName() .
"(" . $this->getId() .
")";