85 public const MOTION_THRESHOLD = 0.00001;
86 protected const STEP_CLIP_MULTIPLIER = 0.4;
88 private const TAG_FIRE =
"Fire";
89 private const TAG_ON_GROUND =
"OnGround";
90 private const TAG_FALL_DISTANCE =
"FallDistance";
91 private const TAG_CUSTOM_NAME =
"CustomName";
92 private const TAG_CUSTOM_NAME_VISIBLE =
"CustomNameVisible";
93 public const TAG_POS =
"Pos";
94 public const TAG_MOTION =
"Motion";
95 public const TAG_ROTATION =
"Rotation";
97 private static int $entityCount = 1;
103 return self::$entityCount++;
107 protected array $hasSpawned = [];
116 protected ?array $blocksAround =
null;
122 protected bool $forceMovementUpdate =
false;
123 private bool $checkBlockIntersectionsNextTick =
true;
126 public bool $onGround =
false;
130 private float $health = 20.0;
131 private int $maxHealth = 20;
133 protected float $ySize = 0.0;
134 protected float $stepHeight = 0.0;
135 public bool $keepMovement =
false;
137 public float $fallDistance = 0.0;
138 public int $ticksLived = 0;
139 public int $lastUpdate;
140 protected int $fireTicks = 0;
142 private bool $savedWithChunk =
true;
144 public bool $isCollided =
false;
145 public bool $isCollidedHorizontally =
false;
146 public bool $isCollidedVertically =
false;
148 public int $noDamageTicks = 0;
149 protected bool $justCreated =
true;
153 protected float $gravity;
154 protected float $drag;
155 protected bool $gravityEnabled =
true;
159 protected bool $closed =
false;
160 private bool $closeInFlight =
false;
161 private bool $needsDespawn =
false;
165 protected bool $networkPropertiesDirty =
false;
167 protected string $nameTag =
"";
168 protected bool $nameTagVisible =
true;
169 protected bool $alwaysShowNameTag =
false;
170 protected string $scoreTag =
"";
171 protected float $scale = 1.0;
173 protected bool $canClimb =
false;
174 protected bool $canClimbWalls =
false;
175 protected bool $noClientPredictions =
false;
176 protected bool $invisible =
false;
177 protected bool $silent =
false;
179 protected ?
int $ownerId =
null;
180 protected ?
int $targetId =
null;
182 private bool $constructorCalled =
false;
185 if($this->constructorCalled){
186 throw new \LogicException(
"Attempted to call constructor for an Entity multiple times");
188 $this->constructorCalled =
true;
189 Utils::checkLocationNotInfOrNaN($location);
191 $this->timings = Timings::getEntityTimings($this);
193 $this->size = $this->getInitialSizeInfo();
194 $this->drag = $this->getInitialDragMultiplier();
195 $this->gravity = $this->getInitialGravity();
197 $this->
id = self::nextRuntimeId();
202 $this->boundingBox =
new AxisAlignedBB(0, 0, 0, 0, 0, 0);
203 $this->recalculateBoundingBox();
208 $this->motion = Vector3::zero();
211 $this->resetLastMovements();
213 $this->networkProperties =
new EntityMetadataCollection();
215 $this->attributeMap =
new AttributeMap();
216 $this->addAttributes();
218 $this->initEntity($nbt ??
new CompoundTag());
220 $this->getWorld()->addEntity($this);
222 $this->lastUpdate = $this->
server->getTick();
224 $this->scheduleUpdate();
227 abstract protected function getInitialSizeInfo() : EntitySizeInfo;
244 public function getNameTag() : string{
245 return $this->nameTag;
248 public function isNameTagVisible() : bool{
249 return $this->nameTagVisible;
252 public function isNameTagAlwaysVisible() : bool{
253 return $this->alwaysShowNameTag;
264 public function setNameTag(
string $name) : void{
265 $this->nameTag = $name;
266 $this->networkPropertiesDirty =
true;
269 public function setNameTagVisible(
bool $value =
true) : void{
270 $this->nameTagVisible = $value;
271 $this->networkPropertiesDirty =
true;
274 public function setNameTagAlwaysVisible(
bool $value =
true) : void{
275 $this->alwaysShowNameTag = $value;
276 $this->networkPropertiesDirty =
true;
279 public function getScoreTag() : ?string{
280 return $this->scoreTag;
283 public function setScoreTag(
string $score) : void{
284 $this->scoreTag = $score;
285 $this->networkPropertiesDirty =
true;
288 public function getScale() : float{
292 public function setScale(
float $value) : void{
294 throw new \InvalidArgumentException(
"Scale must be greater than 0");
296 $this->scale = $value;
297 $this->setSize($this->getInitialSizeInfo()->scale($value));
300 public function getBoundingBox() : AxisAlignedBB{
301 return $this->boundingBox;
304 protected function recalculateBoundingBox() : void{
305 $halfWidth = $this->size->getWidth() / 2;
307 $this->boundingBox =
new AxisAlignedBB(
308 $this->location->x - $halfWidth,
309 $this->location->y + $this->ySize,
310 $this->location->z - $halfWidth,
311 $this->location->x + $halfWidth,
312 $this->location->y + $this->size->getHeight() + $this->ySize,
313 $this->location->z + $halfWidth
317 public function getSize() : EntitySizeInfo{
321 protected function setSize(EntitySizeInfo $size) : void{
323 $this->recalculateBoundingBox();
324 $this->networkPropertiesDirty =
true;
332 return $this->noClientPredictions;
344 $this->noClientPredictions = $value;
345 $this->networkPropertiesDirty =
true;
348 public function isInvisible() : bool{
349 return $this->invisible;
352 public function setInvisible(
bool $value =
true) : void{
353 $this->invisible = $value;
354 $this->networkPropertiesDirty =
true;
357 public function isSilent() : bool{
358 return $this->silent;
361 public function setSilent(
bool $value =
true) : void{
362 $this->silent = $value;
363 $this->networkPropertiesDirty =
true;
370 return $this->canClimb;
377 $this->canClimb = $value;
378 $this->networkPropertiesDirty =
true;
385 return $this->canClimbWalls;
392 $this->canClimbWalls = $value;
393 $this->networkPropertiesDirty =
true;
400 return $this->ownerId;
407 return $this->ownerId !== null ? $this->
server->getWorldManager()->findEntity($this->ownerId) : null;
417 $this->ownerId =
null;
418 }elseif($owner->closed){
419 throw new \InvalidArgumentException(
"Supplied owning entity is garbage and cannot be used");
421 $this->ownerId = $owner->getId();
423 $this->networkPropertiesDirty =
true;
430 return $this->targetId;
438 return $this->targetId !== null ? $this->
server->getWorldManager()->findEntity($this->targetId) : null;
447 if($target === null){
448 $this->targetId =
null;
449 }elseif($target->closed){
450 throw new \InvalidArgumentException(
"Supplied target entity is garbage and cannot be used");
452 $this->targetId = $target->getId();
454 $this->networkPropertiesDirty =
true;
461 return $this->savedWithChunk;
469 $this->savedWithChunk = $value;
474 ->setTag(self::TAG_POS, new
ListTag([
479 ->setTag(self::TAG_MOTION, new
ListTag([
484 ->setTag(self::TAG_ROTATION, new
ListTag([
486 new
FloatTag($this->location->pitch)
489 if(!($this instanceof
Player)){
490 EntityFactory::getInstance()->injectSaveId(get_class($this), $nbt);
492 if($this->getNameTag() !==
""){
493 $nbt->setString(self::TAG_CUSTOM_NAME, $this->getNameTag());
494 $nbt->setByte(self::TAG_CUSTOM_NAME_VISIBLE, $this->isNameTagVisible() ? 1 : 0);
498 $nbt->
setFloat(self::TAG_FALL_DISTANCE, $this->fallDistance);
499 $nbt->setShort(self::TAG_FIRE, $this->fireTicks);
500 $nbt->setByte(self::TAG_ON_GROUND, $this->onGround ? 1 : 0);
502 $nbt->setLong(VersionInfo::TAG_WORLD_DATA_VERSION, VersionInfo::WORLD_DATA_VERSION);
507 protected function initEntity(CompoundTag $nbt) : void{
508 $this->fireTicks = $nbt->getShort(self::TAG_FIRE, 0);
510 $this->onGround = $nbt->getByte(self::TAG_ON_GROUND, 0) !== 0;
512 $this->fallDistance = $nbt->getFloat(self::TAG_FALL_DISTANCE, 0.0);
514 if(($customNameTag = $nbt->getTag(self::TAG_CUSTOM_NAME)) instanceof StringTag){
515 $this->setNameTag($customNameTag->getValue());
517 if(($customNameVisibleTag = $nbt->getTag(self::TAG_CUSTOM_NAME_VISIBLE)) instanceof StringTag){
519 $this->setNameTagVisible($customNameVisibleTag->getValue() !==
"");
521 $this->setNameTagVisible($nbt->getByte(self::TAG_CUSTOM_NAME_VISIBLE, 1) !== 0);
526 protected function addAttributes() : void{
530 public function attack(EntityDamageEvent $source) : void{
531 if($this->isFireProof() && (
532 $source->getCause() === EntityDamageEvent::CAUSE_FIRE ||
533 $source->getCause() === EntityDamageEvent::CAUSE_FIRE_TICK ||
534 $source->getCause() === EntityDamageEvent::CAUSE_LAVA
540 if($source->isCancelled()){
544 $this->setLastDamageCause($source);
546 $this->setHealth($this->getHealth() - $source->getFinalDamage());
549 public function heal(EntityRegainHealthEvent $source) : void{
551 if($source->isCancelled()){
555 $this->setHealth($this->getHealth() + $source->getAmount());
558 public function kill() : void{
559 if($this->isAlive()){
562 $this->scheduleUpdate();
576 protected function onDeathUpdate(int $tickDiff) : bool{
580 public function isAlive() : bool{
581 return $this->health > 0;
584 public function getHealth() : float{
585 return $this->health;
592 if($amount == $this->health){
597 if($this->isAlive()){
598 if(!$this->justCreated){
604 }elseif($amount <= $this->getMaxHealth() || $amount < $this->health){
605 $this->health = $amount;
607 $this->health = $this->getMaxHealth();
611 public function getMaxHealth() : int{
612 return $this->maxHealth;
615 public function setMaxHealth(
int $amount) : void{
616 $this->maxHealth = $amount;
619 public function setLastDamageCause(EntityDamageEvent $type) : void{
620 $this->lastDamageCause = $type;
623 public function getLastDamageCause() : ?EntityDamageEvent{
624 return $this->lastDamageCause;
627 public function getAttributeMap() : AttributeMap{
628 return $this->attributeMap;
631 public function getNetworkProperties() : EntityMetadataCollection{
632 return $this->networkProperties;
635 protected function entityBaseTick(
int $tickDiff = 1) : bool{
638 if($this->justCreated){
639 $this->justCreated =
false;
640 if(!$this->isAlive()){
645 $changedProperties = $this->getDirtyNetworkData();
646 if(count($changedProperties) > 0){
647 $this->sendData(
null, $changedProperties);
648 $this->networkProperties->clearDirtyProperties();
653 if($this->checkBlockIntersectionsNextTick){
654 $this->checkBlockIntersections();
656 $this->checkBlockIntersectionsNextTick =
true;
658 if($this->location->y <= World::Y_MIN - 16 && $this->isAlive()){
659 $ev =
new EntityDamageEvent($this, EntityDamageEvent::CAUSE_VOID, 10);
664 if($this->isOnFire() && $this->doOnFireTick($tickDiff)){
668 if($this->noDamageTicks > 0){
669 $this->noDamageTicks -= $tickDiff;
670 if($this->noDamageTicks < 0){
671 $this->noDamageTicks = 0;
675 $this->ticksLived += $tickDiff;
680 public function isOnFire() : bool{
681 return $this->fireTicks > 0;
684 public function setOnFire(
int $seconds) : void{
685 $ticks = $seconds * 20;
686 if($ticks > $this->getFireTicks()){
687 $this->setFireTicks($ticks);
689 $this->networkPropertiesDirty =
true;
692 public function getFireTicks() : int{
693 return $this->fireTicks;
700 if($fireTicks < 0 || $fireTicks > 0x7fff){
701 throw new \InvalidArgumentException(
"Fire ticks must be in range 0 ... " . 0x7fff .
", got $fireTicks");
703 if(!$this->isFireProof()){
704 $this->fireTicks = $fireTicks;
705 $this->networkPropertiesDirty =
true;
709 public function extinguish() : void{
710 $this->fireTicks = 0;
711 $this->networkPropertiesDirty =
true;
714 public function isFireProof() : bool{
718 protected function doOnFireTick(
int $tickDiff = 1) : bool{
719 if($this->isFireProof() && $this->isOnFire()){
724 $this->fireTicks -= $tickDiff;
726 if(($this->fireTicks % 20 === 0) || $tickDiff > 20){
727 $this->dealFireDamage();
730 if(!$this->isOnFire()){
747 public function canCollideWith(
Entity $entity) : bool{
748 return !$this->justCreated && $entity !== $this;
751 public function canBeCollidedWith() : bool{
752 return $this->isAlive();
755 protected function updateMovement(
bool $teleport =
false) : void{
756 $diffPosition = $this->location->distanceSquared($this->lastLocation);
757 $diffRotation = ($this->location->yaw - $this->lastLocation->yaw) ** 2 + ($this->location->pitch - $this->lastLocation->pitch) ** 2;
759 $diffMotion = $this->motion->subtractVector($this->lastMotion)->lengthSquared();
761 $still = $this->motion->lengthSquared() == 0.0;
762 $wasStill = $this->lastMotion->lengthSquared() == 0.0;
763 if($wasStill !== $still){
765 $this->setNoClientPredictions($still);
768 if($teleport || $diffPosition > 0.0001 || $diffRotation > 1.0 || (!$wasStill && $still)){
769 $this->lastLocation = $this->location->asLocation();
771 $this->broadcastMovement($teleport);
774 if($diffMotion > 0.0025 || $wasStill !== $still){
775 $this->lastMotion = clone $this->motion;
777 $this->broadcastMotion();
781 public function getOffsetPosition(Vector3 $vector3) : Vector3{
785 protected function broadcastMovement(
bool $teleport =
false) : void{
786 NetworkBroadcastUtils::broadcastPackets($this->hasSpawned, [MoveActorAbsolutePacket::create(
788 $this->getOffsetPosition($this->location),
789 $this->location->pitch,
790 $this->location->yaw,
791 $this->location->yaw,
798 ($this->onGround ? MoveActorAbsolutePacket::FLAG_GROUND : 0)
803 protected function broadcastMotion() : void{
804 NetworkBroadcastUtils::broadcastPackets($this->hasSpawned, [SetActorMotionPacket::create($this->id, $this->getMotion(), tick: 0)]);
807 public function getGravity() : float{
808 return $this->gravity;
811 public function setGravity(
float $gravity) : void{
812 Utils::checkFloatNotInfOrNaN(
"gravity", $gravity);
813 $this->gravity = $gravity;
816 public function hasGravity() : bool{
817 return $this->gravityEnabled;
820 public function setHasGravity(
bool $v =
true) : void{
821 $this->gravityEnabled = $v;
824 protected function applyDragBeforeGravity() : bool{
828 protected function tryChangeMovement() : void{
829 $friction = 1 - $this->drag;
831 $mY = $this->motion->y;
833 if($this->applyDragBeforeGravity()){
837 if($this->gravityEnabled){
838 $mY -= $this->gravity;
841 if(!$this->applyDragBeforeGravity()){
846 $friction *= $this->getWorld()->getBlockAt((
int) floor($this->location->x), (
int) floor($this->location->y - 1), (
int) floor($this->location->z))->getFrictionFactor();
849 $this->motion =
new Vector3($this->motion->x * $friction, $mY, $this->motion->z * $friction);
852 protected function checkObstruction(
float $x,
float $y,
float $z) : bool{
853 $world = $this->getWorld();
854 if(count($world->getBlockCollisionBoxes($this->boundingBox)) === 0){
858 $floorX = (
int) floor($x);
859 $floorY = (int) floor($y);
860 $floorZ = (int) floor($z);
862 $diffX = $x - $floorX;
863 $diffY = $y - $floorY;
864 $diffZ = $z - $floorZ;
866 if($world->getBlockAt($floorX, $floorY, $floorZ)->isSolid()){
867 $westNonSolid = !$world->getBlockAt($floorX - 1, $floorY, $floorZ)->isSolid();
868 $eastNonSolid = !$world->getBlockAt($floorX + 1, $floorY, $floorZ)->isSolid();
869 $downNonSolid = !$world->getBlockAt($floorX, $floorY - 1, $floorZ)->isSolid();
870 $upNonSolid = !$world->getBlockAt($floorX, $floorY + 1, $floorZ)->isSolid();
871 $northNonSolid = !$world->getBlockAt($floorX, $floorY, $floorZ - 1)->isSolid();
872 $southNonSolid = !$world->getBlockAt($floorX, $floorY, $floorZ + 1)->isSolid();
879 $direction = Facing::WEST;
882 if($eastNonSolid && 1 - $diffX < $limit){
884 $direction = Facing::EAST;
887 if($downNonSolid && $diffY < $limit){
889 $direction = Facing::DOWN;
892 if($upNonSolid && 1 - $diffY < $limit){
894 $direction = Facing::UP;
897 if($northNonSolid && $diffZ < $limit){
899 $direction = Facing::NORTH;
902 if($southNonSolid && 1 - $diffZ < $limit){
903 $direction = Facing::SOUTH;
906 if($direction === -1){
910 $force = lcg_value() * 0.2 + 0.1;
912 $this->motion = match($direction){
913 Facing::WEST => $this->motion->withComponents(-$force,
null,
null),
914 Facing::EAST => $this->motion->withComponents($force,
null,
null),
915 Facing::DOWN => $this->motion->withComponents(
null, -$force,
null),
916 Facing::UP => $this->motion->withComponents(
null, $force,
null),
917 Facing::NORTH => $this->motion->withComponents(
null,
null, -$force),
918 Facing::SOUTH => $this->motion->withComponents(
null,
null, $force),
926 public function getHorizontalFacing() : int{
927 $angle = fmod($this->location->yaw, 360);
932 if((0 <= $angle && $angle < 45) || (315 <= $angle && $angle < 360)){
933 return Facing::SOUTH;
935 if(45 <= $angle && $angle < 135){
938 if(135 <= $angle && $angle < 225){
939 return Facing::NORTH;
945 public function getDirectionVector() : Vector3{
946 $y = -sin(deg2rad($this->location->pitch));
947 $xz = cos(deg2rad($this->location->pitch));
948 $x = -$xz * sin(deg2rad($this->location->yaw));
949 $z = $xz * cos(deg2rad($this->location->yaw));
951 return (
new Vector3($x, $y, $z))->normalize();
954 public function getDirectionPlane() : Vector2{
955 return (new Vector2(-cos(deg2rad($this->location->yaw) - M_PI_2), -sin(deg2rad($this->location->yaw) - M_PI_2)))->normalize();
966 public function onUpdate(
int $currentTick) : bool{
971 $tickDiff = $currentTick - $this->lastUpdate;
973 if(!$this->justCreated){
974 $this->
server->getLogger()->debug(
"Expected tick difference of at least 1, got $tickDiff for " . get_class($this));
980 $this->lastUpdate = $currentTick;
982 if($this->justCreated){
983 $this->onFirstUpdate($currentTick);
986 if(!$this->isAlive()){
987 if($this->onDeathUpdate($tickDiff)){
988 $this->flagForDespawn();
994 $this->timings->startTiming();
996 if($this->hasMovementUpdate()){
997 $this->tryChangeMovement();
999 $this->motion = $this->motion->withComponents(
1000 abs($this->motion->x) <= self::MOTION_THRESHOLD ? 0 :
null,
1001 abs($this->motion->y) <= self::MOTION_THRESHOLD ? 0 :
null,
1002 abs($this->motion->z) <= self::MOTION_THRESHOLD ? 0 :
null
1005 if($this->motion->x != 0 || $this->motion->y != 0 || $this->motion->z != 0){
1006 $this->move($this->motion->x, $this->motion->y, $this->motion->z);
1009 $this->forceMovementUpdate =
false;
1012 $this->updateMovement();
1014 Timings::$entityBaseTick->startTiming();
1015 $hasUpdate = $this->entityBaseTick($tickDiff);
1016 Timings::$entityBaseTick->stopTiming();
1018 $this->timings->stopTiming();
1020 return ($hasUpdate || $this->hasMovementUpdate());
1023 final public function scheduleUpdate() : void{
1025 throw new \LogicException(
"Cannot schedule update on garbage entity " . get_class($this));
1027 $this->getWorld()->updateEntities[$this->id] = $this;
1030 public function onNearbyBlockChange() : void{
1031 $this->setForceMovementUpdate();
1032 $this->scheduleUpdate();
1040 $this->scheduleUpdate();
1048 $this->forceMovementUpdate = $value;
1050 $this->blocksAround =
null;
1058 $this->forceMovementUpdate ||
1059 $this->motion->x != 0 ||
1060 $this->motion->y != 0 ||
1061 $this->motion->z != 0 ||
1066 public function getFallDistance() : float{ return $this->fallDistance; }
1068 public function setFallDistance(
float $fallDistance) : void{
1069 $this->fallDistance = $fallDistance;
1072 public function resetFallDistance() : void{
1073 $this->fallDistance = 0.0;
1076 protected function updateFallState(
float $distanceThisTick,
bool $onGround) : ?float{
1077 if($distanceThisTick < $this->fallDistance){
1080 $this->fallDistance -= $distanceThisTick;
1084 $this->fallDistance = 0;
1086 if($onGround && $this->fallDistance > 0){
1087 $newVerticalVelocity = $this->onHitGround();
1088 $this->resetFallDistance();
1089 return $newVerticalVelocity;
1101 public function getEyeHeight() : float{
1102 return $this->size->getEyeHeight();
1105 public function getEyePos() : Vector3{
1106 return new Vector3($this->location->x, $this->location->y + $this->getEyeHeight(), $this->location->z);
1109 public function onCollideWithPlayer(Player $player) : void{
1120 public function isUnderwater() : bool{
1121 $block = $this->getWorld()->getBlockAt((int) floor($this->location->x), $blockY = (int) floor($y = ($this->location->y + $this->getEyeHeight())), (int) floor($this->location->z));
1123 if($block instanceof
Water){
1124 $f = ($blockY + 1) - ($block->getFluidHeightPercent() - 0.1111111);
1131 public function isInsideOfSolid() : bool{
1132 $block = $this->getWorld()->getBlockAt((int) floor($this->location->x), (int) floor($y = ($this->location->y + $this->getEyeHeight())), (int) floor($this->location->z));
1134 return $block->isSolid() && !$block->isTransparent() && $block->collidesWithBB($this->getBoundingBox());
1137 protected function move(
float $dx,
float $dy,
float $dz) : void{
1138 $this->blocksAround = null;
1140 Timings::$entityMove->startTiming();
1141 Timings::$entityMoveCollision->startTiming();
1147 if($this->keepMovement){
1148 $this->boundingBox->offset($dx, $dy, $dz);
1150 $this->ySize *= self::STEP_CLIP_MULTIPLIER;
1152 $moveBB = clone $this->boundingBox;
1154 assert(abs($dx) <= 20 && abs($dy) <= 20 && abs($dz) <= 20,
"Movement distance is excessive: dx=$dx, dy=$dy, dz=$dz");
1156 $list = $this->getWorld()->getBlockCollisionBoxes($moveBB->addCoord($dx, $dy, $dz));
1158 foreach($list as $bb){
1159 $dy = $bb->calculateYOffset($moveBB, $dy);
1162 $moveBB->offset(0, $dy, 0);
1164 $fallingFlag = ($this->onGround || ($dy != $wantedY && $wantedY < 0));
1166 foreach($list as $bb){
1167 $dx = $bb->calculateXOffset($moveBB, $dx);
1170 $moveBB->offset($dx, 0, 0);
1172 foreach($list as $bb){
1173 $dz = $bb->calculateZOffset($moveBB, $dz);
1176 $moveBB->offset(0, 0, $dz);
1178 if($this->stepHeight > 0 && $fallingFlag && ($wantedX != $dx || $wantedZ != $dz)){
1183 $dy = $this->stepHeight;
1186 $stepBB = clone $this->boundingBox;
1188 $list = $this->getWorld()->getBlockCollisionBoxes($stepBB->addCoord($dx, $dy, $dz));
1189 foreach($list as $bb){
1190 $dy = $bb->calculateYOffset($stepBB, $dy);
1193 $stepBB->offset(0, $dy, 0);
1195 foreach($list as $bb){
1196 $dx = $bb->calculateXOffset($stepBB, $dx);
1199 $stepBB->offset($dx, 0, 0);
1201 foreach($list as $bb){
1202 $dz = $bb->calculateZOffset($stepBB, $dz);
1205 $stepBB->offset(0, 0, $dz);
1208 foreach($list as $bb){
1209 $reverseDY = $bb->calculateYOffset($stepBB, $reverseDY);
1212 $stepBB->offset(0, $reverseDY, 0);
1214 if(($cx ** 2 + $cz ** 2) >= ($dx ** 2 + $dz ** 2)){
1220 $this->ySize += $dy;
1224 $this->boundingBox = $moveBB;
1226 Timings::$entityMoveCollision->stopTiming();
1228 $this->location =
new Location(
1229 ($this->boundingBox->minX + $this->boundingBox->maxX) / 2,
1230 $this->boundingBox->minY - $this->ySize,
1231 ($this->boundingBox->minZ + $this->boundingBox->maxZ) / 2,
1232 $this->location->world,
1233 $this->location->yaw,
1234 $this->location->pitch
1237 $this->getWorld()->onEntityMoved($this);
1238 $this->checkBlockIntersections();
1239 $this->checkGroundState($wantedX, $wantedY, $wantedZ, $dx, $dy, $dz);
1240 $postFallVerticalVelocity = $this->updateFallState($dy, $this->onGround);
1242 $this->motion = $this->motion->withComponents(
1243 $wantedX != $dx ? 0 :
null,
1244 $postFallVerticalVelocity ?? ($wantedY != $dy ? 0 :
null),
1245 $wantedZ != $dz ? 0 :
null
1250 Timings::$entityMove->stopTiming();
1253 protected function checkGroundState(
float $wantedX,
float $wantedY,
float $wantedZ,
float $dx,
float $dy,
float $dz) : void{
1254 $this->isCollidedVertically = $wantedY != $dy;
1255 $this->isCollidedHorizontally = ($wantedX != $dx || $wantedZ != $dz);
1256 $this->isCollided = ($this->isCollidedHorizontally || $this->isCollidedVertically);
1257 $this->onGround = ($wantedY != $dy && $wantedY < 0);
1266 $minX = (int) floor($this->boundingBox->minX + $inset);
1267 $minY = (int) floor($this->boundingBox->minY + $inset);
1268 $minZ = (int) floor($this->boundingBox->minZ + $inset);
1269 $maxX = (int) floor($this->boundingBox->maxX - $inset);
1270 $maxY = (int) floor($this->boundingBox->maxY - $inset);
1271 $maxZ = (int) floor($this->boundingBox->maxZ - $inset);
1273 $world = $this->getWorld();
1275 for($z = $minZ; $z <= $maxZ; ++$z){
1276 for($x = $minX; $x <= $maxX; ++$x){
1277 for($y = $minY; $y <= $maxY; ++$y){
1278 yield $world->getBlockAt($x, $y, $z);
1288 if($this->blocksAround === null){
1289 $this->blocksAround = [];
1292 foreach($this->getBlocksIntersected($inset) as $block){
1293 if($block->hasEntityCollision()){
1294 $this->blocksAround[] = $block;
1299 return $this->blocksAround;
1309 protected function checkBlockIntersections() : void{
1310 $this->checkBlockIntersectionsNextTick = false;
1313 foreach($this->getBlocksAroundWithEntityInsideActions() as $block){
1314 if(!$block->onEntityInside($this)){
1315 $this->blocksAround =
null;
1317 if(($v = $block->addVelocityToEntity($this)) !==
null){
1322 if(count($vectors) > 0){
1323 $vector = Vector3::sum(...$vectors);
1324 if($vector->lengthSquared() > 0){
1326 $this->motion = $this->motion->addVector($vector->normalize()->multiply($d));
1332 return $this->location->asPosition();
1335 public function getLocation() : Location{
1336 return $this->location->asLocation();
1339 public function getWorld() : World{
1340 return $this->location->getWorld();
1343 protected function setPosition(Vector3 $pos) : bool{
1348 $oldWorld = $this->getWorld();
1349 $newWorld = $pos instanceof Position ? $pos->getWorld() : $oldWorld;
1350 if($oldWorld !== $newWorld){
1351 $this->despawnFromAll();
1352 $oldWorld->removeEntity($this);
1355 $this->location = Location::fromObject(
1358 $this->location->yaw,
1359 $this->location->pitch
1362 $this->recalculateBoundingBox();
1364 $this->blocksAround =
null;
1366 if($oldWorld !== $newWorld){
1367 $newWorld->addEntity($this);
1369 $newWorld->onEntityMoved($this);
1375 public function setRotation(
float $yaw,
float $pitch) : void{
1376 Utils::checkFloatNotInfOrNaN(
"yaw", $yaw);
1377 Utils::checkFloatNotInfOrNaN(
"pitch", $pitch);
1378 $this->location->yaw = $yaw;
1379 $this->location->pitch = $pitch;
1380 $this->scheduleUpdate();
1383 protected function setPositionAndRotation(Vector3 $pos,
float $yaw,
float $pitch) : bool{
1384 if($this->setPosition($pos)){
1385 $this->setRotation($yaw, $pitch);
1393 protected function resetLastMovements() : void{
1394 $this->lastLocation = $this->location->asLocation();
1395 $this->lastMotion = clone $this->motion;
1398 public function getMotion() : Vector3{
1399 return clone $this->motion;
1402 public function setMotion(Vector3 $motion) : bool{
1403 Utils::checkVector3NotInfOrNaN($motion);
1404 if(!$this->justCreated){
1405 $ev =
new EntityMotionEvent($this, $motion);
1407 if($ev->isCancelled()){
1412 $this->motion = clone $motion;
1414 if(!$this->justCreated){
1415 $this->updateMovement();
1424 public function addMotion(
float $x,
float $y,
float $z) : void{
1425 Utils::checkFloatNotInfOrNaN(
"x", $x);
1426 Utils::checkFloatNotInfOrNaN(
"y", $y);
1427 Utils::checkFloatNotInfOrNaN(
"z", $z);
1428 $this->motion = $this->motion->add($x, $y, $z);
1431 public function isOnGround() : bool{
1432 return $this->onGround;
1439 Utils::checkVector3NotInfOrNaN($pos);
1441 $yaw = $yaw ?? $pos->yaw;
1442 $pitch = $pitch ?? $pos->pitch;
1445 Utils::checkFloatNotInfOrNaN(
"yaw", $yaw);
1447 if($pitch !==
null){
1448 Utils::checkFloatNotInfOrNaN(
"pitch", $pitch);
1451 $from = $this->location->asPosition();
1452 $to = Position::fromObject($pos, $pos instanceof Position ? $pos->getWorld() : $this->getWorld());
1453 $ev =
new EntityTeleportEvent($this, $from, $to);
1455 if($ev->isCancelled()){
1459 $pos = $ev->getTo();
1461 $this->setMotion(
new Vector3(0, 0, 0));
1462 if($this->setPositionAndRotation($pos, $yaw ?? $this->location->yaw, $pitch ?? $this->location->pitch)){
1463 $this->resetFallDistance();
1464 $this->setForceMovementUpdate();
1466 $this->updateMovement(
true);
1474 public function getId() : int{
1482 return $this->hasSpawned;
1485 abstract public function getNetworkTypeId() : string;
1491 $player->getNetworkSession()->sendDataPacket(
AddActorPacket::create(
1494 $this->getNetworkTypeId(),
1495 $this->location->asVector3(),
1497 $this->location->pitch,
1498 $this->location->yaw,
1499 $this->location->yaw,
1500 $this->location->yaw,
1501 array_map(function(
Attribute $attr) : NetworkAttribute{
1502 return new NetworkAttribute($attr->getId(), $attr->getMinValue(), $attr->getMaxValue(), $attr->getValue(), $attr->getDefaultValue(), []);
1503 }, $this->attributeMap->getAll()),
1504 $this->getAllNetworkData(),
1510 public function spawnTo(
Player $player) : void{
1511 $id = spl_object_id($player);
1515 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)){
1516 $this->hasSpawned[$id] = $player;
1518 $this->sendSpawnPacket($player);
1522 public function spawnToAll() : void{
1526 foreach($this->getWorld()->getViewersForPosition($this->location) as $player){
1527 $this->spawnTo($player);
1531 public function respawnToAll() : void{
1532 foreach($this->hasSpawned as $key => $player){
1533 unset($this->hasSpawned[$key]);
1534 $this->spawnTo($player);
1543 $id = spl_object_id($player);
1544 if(isset($this->hasSpawned[$id])){
1546 $player->getNetworkSession()->getEntityEventBroadcaster()->onEntityRemoved([$player->getNetworkSession()], $this);
1548 unset($this->hasSpawned[$id]);
1559 fn(
EntityEventBroadcaster $broadcaster, array $recipients) => $broadcaster->onEntityRemoved($recipients, $this)
1561 $this->hasSpawned = [];
1575 $this->needsDespawn = true;
1576 $this->scheduleUpdate();
1579 public function isFlaggedForDespawn() : bool{
1580 return $this->needsDespawn;
1587 return $this->closed;
1596 if($this->closeInFlight){
1601 $this->closeInFlight =
true;
1605 $this->closed =
true;
1606 $this->destroyCycles();
1607 $this->closeInFlight =
false;
1616 $this->despawnFromAll();
1617 if($this->location->isValid()){
1618 $this->getWorld()->removeEntity($this);
1629 $this->lastDamageCause = null;
1638 public function sendData(?array $targets, ?array $data =
null) : void{
1639 $targets = $targets ?? $this->hasSpawned;
1640 $data = $data ?? $this->getAllNetworkData();
1642 NetworkBroadcastUtils::broadcastEntityEvent($targets, fn(
EntityEventBroadcaster $broadcaster, array $recipients) => $broadcaster->
syncActorData($recipients, $this, $data));
1650 if($this->networkPropertiesDirty){
1651 $this->syncNetworkData($this->networkProperties);
1652 $this->networkPropertiesDirty =
false;
1654 return $this->networkProperties->getDirty();
1662 if($this->networkPropertiesDirty){
1663 $this->syncNetworkData($this->networkProperties);
1664 $this->networkPropertiesDirty =
false;
1666 return $this->networkProperties->getAll();
1669 protected function syncNetworkData(EntityMetadataCollection $properties) : void{
1670 $properties->setByte(EntityMetadataProperties::ALWAYS_SHOW_NAMETAG, $this->alwaysShowNameTag ? 1 : 0);
1671 $properties->setFloat(EntityMetadataProperties::BOUNDING_BOX_HEIGHT, $this->size->getHeight() / $this->scale);
1672 $properties->setFloat(EntityMetadataProperties::BOUNDING_BOX_WIDTH, $this->size->getWidth() / $this->scale);
1673 $properties->setFloat(EntityMetadataProperties::SCALE, $this->scale);
1674 $properties->setLong(EntityMetadataProperties::LEAD_HOLDER_EID, -1);
1675 $properties->setLong(EntityMetadataProperties::OWNER_EID, $this->ownerId ?? -1);
1676 $properties->setLong(EntityMetadataProperties::TARGET_EID, $this->targetId ?? 0);
1677 $properties->setString(EntityMetadataProperties::NAMETAG, $this->nameTag);
1678 $properties->setString(EntityMetadataProperties::SCORE_TAG, $this->scoreTag);
1679 $properties->setByte(EntityMetadataProperties::COLOR, 0);
1681 $properties->setGenericFlag(EntityMetadataFlags::AFFECTED_BY_GRAVITY, $this->gravityEnabled);
1682 $properties->setGenericFlag(EntityMetadataFlags::CAN_CLIMB, $this->canClimb);
1683 $properties->setGenericFlag(EntityMetadataFlags::CAN_SHOW_NAMETAG, $this->nameTagVisible);
1684 $properties->setGenericFlag(EntityMetadataFlags::HAS_COLLISION,
true);
1685 $properties->setGenericFlag(EntityMetadataFlags::NO_AI, $this->noClientPredictions);
1686 $properties->setGenericFlag(EntityMetadataFlags::INVISIBLE, $this->invisible);
1687 $properties->setGenericFlag(EntityMetadataFlags::SILENT, $this->silent);
1688 $properties->setGenericFlag(EntityMetadataFlags::ONFIRE, $this->isOnFire());
1689 $properties->setGenericFlag(EntityMetadataFlags::WALLCLIMBING, $this->canClimbWalls);
1705 $this->getWorld()->addSound($this->location->asVector3(), $sound, $targets ?? $this->getViewers());
1709 public function __destruct(){
1713 public function __toString(){
1714 return (
new \ReflectionClass($this))->getShortName() .
"(" . $this->getId() .
")";