1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
|
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "IncludeAllMonsters.h"
#include "LineBlockTracer.h"
#include "../BlockInfo.h"
#include "../Root.h"
#include "../Server.h"
#include "../ClientHandle.h"
#include "../Items/ItemHandler.h"
#include "../World.h"
#include "../EffectID.h"
#include "../Entities/Player.h"
#include "../Entities/ExpOrb.h"
#include "../MonsterConfig.h"
#include "../BoundingBox.h"
#include "Items/ItemSpawnEgg.h"
#include "../Chunk.h"
#include "../FastRandom.h"
#include "PathFinder.h"
#include "../Entities/LeashKnot.h"
/** Map for eType <-> string
Needs to be alpha-sorted by the strings, because binary search is used in StringToMobType()
The strings need to be lowercase (for more efficient comparisons in StringToMobType())
m_VanillaName is the name that vanilla use for this mob.
*/
static const struct
{
eMonsterType m_Type;
const char * m_lcName;
const char * m_VanillaName;
const char * m_VanillaNameNBT;
} g_MobTypeNames[] =
{
{mtBat, "bat", "Bat", "bat"},
{mtBlaze, "blaze", "Blaze", "blaze"},
{mtCaveSpider, "cavespider", "CaveSpider", "cave_spider"},
{mtChicken, "chicken", "Chicken", "chicken"},
{mtCow, "cow", "Cow", "cow"},
{mtCreeper, "creeper", "Creeper", "creeper"},
{mtEnderman, "enderman", "Enderman", "enderman"},
{mtEnderDragon, "enderdragon", "EnderDragon", "ender_dragon"},
{mtGhast, "ghast", "Ghast", "ghast"},
{mtGiant, "giant", "Giant", "giant"},
{mtGuardian, "guardian", "Guardian", "guardian"},
{mtHorse, "horse", "EntityHorse", "horse"},
{mtIronGolem, "irongolem", "VillagerGolem", "iron_golem"},
{mtMagmaCube, "magmacube", "LavaSlime", "magma_cube"},
{mtMooshroom, "mooshroom", "MushroomCow", "mooshroom"},
{mtOcelot, "ocelot", "Ozelot", "ocelot"},
{mtPig, "pig", "Pig", "pig"},
{mtRabbit, "rabbit", "Rabbit", "rabbit"},
{mtSheep, "sheep", "Sheep", "sheep"},
{mtSilverfish, "silverfish", "Silverfish", "silverfish"},
{mtSkeleton, "skeleton", "Skeleton", "skeleton"},
{mtSlime, "slime", "Slime", "slime"},
{mtSnowGolem, "snowgolem", "SnowMan", "snow_golem"},
{mtSpider, "spider", "Spider", "spider"},
{mtSquid, "squid", "Squid", "squid"},
{mtVillager, "villager", "Villager", "villager"},
{mtWitch, "witch", "Witch", "witch"},
{mtWither, "wither", "WitherBoss", "wither"},
{mtWitherSkeleton, "witherskeleton", "WitherSkeleton", "wither_skeleton"},
{mtWolf, "wolf", "Wolf", "wolf"},
{mtZombie, "zombie", "Zombie", "zombie"},
{mtZombiePigman, "zombiepigman", "PigZombie", "zombie_pigman"},
{mtZombieVillager, "zombievillager", "ZombieVillager", "zombie_villager"},
} ;
////////////////////////////////////////////////////////////////////////////////
// cMonster:
cMonster::cMonster(const AString & a_ConfigName, eMonsterType a_MobType, const AString & a_SoundHurt, const AString & a_SoundDeath, const AString & a_SoundAmbient, float a_Width, float a_Height)
: Super(etMonster, a_Width, a_Height)
, m_EMState(IDLE)
, m_EMPersonality(AGGRESSIVE)
, m_PathFinder(a_Width, a_Height)
, m_PathfinderActivated(false)
, m_JumpCoolDown(0)
, m_IdleInterval(0)
, m_DestroyTimer(0)
, m_MobType(a_MobType)
, m_CustomName()
, m_CustomNameAlwaysVisible(false)
, m_SoundHurt(a_SoundHurt)
, m_SoundDeath(a_SoundDeath)
, m_SoundAmbient(a_SoundAmbient)
, m_AttackRate(3)
, m_AttackDamage(1)
, m_AttackRange(1)
, m_AttackCoolDownTicksLeft(0)
, m_SightDistance(25)
, m_DropChanceWeapon(0.085f)
, m_DropChanceHelmet(0.085f)
, m_DropChanceChestplate(0.085f)
, m_DropChanceLeggings(0.085f)
, m_DropChanceBoots(0.085f)
, m_CanPickUpLoot(true)
, m_TicksSinceLastDamaged(100)
, m_BurnsInDaylight(false)
, m_RelativeWalkSpeed(1)
, m_Age(1)
, m_AgingTimer(TPS * 60 * 20) // about 20 minutes
, m_WasLastTargetAPlayer(false)
, m_LeashedTo(nullptr)
, m_LeashToPos(nullptr)
, m_IsLeashActionJustDone(false)
, m_CanBeLeashed(GetMobFamily() == eFamily::mfPassive)
, m_LovePartner(nullptr)
, m_LoveTimer(0)
, m_LoveCooldown(0)
, m_MatingTimer(0)
, m_Target(nullptr)
{
if (!a_ConfigName.empty())
{
GetMonsterConfig(a_ConfigName);
}
// Prevent mobs spawning at the same time from making sounds simultaneously
m_AmbientSoundTimer = GetRandomProvider().RandInt(0, 100);
}
void cMonster::OnRemoveFromWorld(cWorld & a_World)
{
SetTarget(nullptr); // Tell them we're no longer targeting them.
if (m_LovePartner != nullptr)
{
m_LovePartner->ResetLoveMode();
}
if (IsLeashed())
{
cEntity * LeashedTo = GetLeashedTo();
Unleash(false, true);
// Remove leash knot if there are no more mobs leashed to
if (!LeashedTo->HasAnyMobLeashed() && LeashedTo->IsLeashKnot())
{
LeashedTo->Destroy();
}
}
Super::OnRemoveFromWorld(a_World);
}
void cMonster::SpawnOn(cClientHandle & a_Client)
{
a_Client.SendSpawnMob(*this);
if (IsLeashed())
{
a_Client.SendLeashEntity(*this, *this->GetLeashedTo());
}
}
void cMonster::MoveToWayPoint(cChunk & a_Chunk)
{
if ((m_NextWayPointPosition - GetPosition()).SqrLength() < WAYPOINT_RADIUS * WAYPOINT_RADIUS)
{
return;
}
if (m_JumpCoolDown <= 0)
{
if (DoesPosYRequireJump(FloorC(m_NextWayPointPosition.y)))
{
if (
(IsOnGround() && (GetSpeed().SqrLength() <= 0.5)) || // If walking on the ground, we need to slow down first, otherwise we miss the jump
IsInWater()
)
{
m_bOnGround = false;
m_JumpCoolDown = 20;
AddPosY(1.6); // Jump!!
SetSpeedY(1);
SetSpeedX(3.2 * (m_NextWayPointPosition.x - GetPosition().x)); // Move forward in a preset speed.
SetSpeedZ(3.2 * (m_NextWayPointPosition.z - GetPosition().z)); // The numbers were picked based on trial and error
}
}
}
else
{
--m_JumpCoolDown;
}
Vector3d Distance = m_NextWayPointPosition - GetPosition();
if ((std::abs(Distance.x) > 0.05) || (std::abs(Distance.z) > 0.05))
{
Distance.y = 0;
Distance.Normalize();
if (m_bOnGround)
{
Distance *= 2.5f;
}
else if (IsInWater())
{
Distance *= 1.3f;
}
else
{
// Don't let the mob move too much if he's falling.
Distance *= 0.25f;
}
// Apply walk speed:
Distance *= m_RelativeWalkSpeed;
/* Reduced default speed.
Close to Vanilla, easier for mobs to follow m_NextWayPointPositions, hence
better pathfinding. */
Distance *= 0.5;
AddSpeedX(Distance.x);
AddSpeedZ(Distance.z);
}
}
void cMonster::MoveToPosition(const Vector3d & a_Position)
{
m_FinalDestination = a_Position;
m_PathfinderActivated = true;
}
void cMonster::StopMovingToPosition()
{
m_PathfinderActivated = false;
}
void cMonster::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
{
Super::Tick(a_Dt, a_Chunk);
if (!IsTicking())
{
// The base class tick destroyed us
return;
}
GET_AND_VERIFY_CURRENT_CHUNK(Chunk, POSX_TOINT, POSZ_TOINT);
ASSERT((GetTarget() == nullptr) || (GetTarget()->IsPawn() && (GetTarget()->GetWorld() == GetWorld())));
if (m_AttackCoolDownTicksLeft > 0)
{
m_AttackCoolDownTicksLeft -= 1;
}
if (m_Health <= 0)
{
// The mob is dead, but we're still animating the "puff" they leave when they die
m_DestroyTimer += a_Dt;
if (m_DestroyTimer > std::chrono::seconds(1))
{
Destroy();
}
return;
}
if (m_TicksSinceLastDamaged < 100)
{
++m_TicksSinceLastDamaged;
}
// Process the undead burning in daylight.
HandleDaylightBurning(*Chunk, WouldBurnAt(GetPosition(), *Chunk));
bool a_IsFollowingPath = false;
if (m_PathfinderActivated && (GetMobType() != mtGhast)) // Pathfinder is currently disabled for ghasts, which have their own flying mechanism
{
if (ReachedFinalDestination() || (m_LeashToPos != nullptr))
{
StopMovingToPosition(); // Simply sets m_PathfinderActivated to false.
}
else
{
// Note that m_NextWayPointPosition is actually returned by GetNextWayPoint)
switch (m_PathFinder.GetNextWayPoint(*Chunk, GetPosition(), &m_FinalDestination, &m_NextWayPointPosition, m_EMState == IDLE))
{
case ePathFinderStatus::PATH_FOUND:
{
/* If I burn in daylight, and I won't burn where I'm standing, and I'll burn in my next position, and at least one of those is true:
1. I am idle
2. I was not hurt by a player recently.
Then STOP. */
if (
m_BurnsInDaylight && ((m_TicksSinceLastDamaged >= 100) || (m_EMState == IDLE)) &&
WouldBurnAt(m_NextWayPointPosition, *Chunk) &&
!WouldBurnAt(GetPosition(), *Chunk)
)
{
// If we burn in daylight, and we would burn at the next step, and we won't burn where we are right now, and we weren't provoked recently:
StopMovingToPosition();
}
else
{
a_IsFollowingPath = true; // Used for proper body / head orientation only.
MoveToWayPoint(*Chunk);
}
break;
}
case ePathFinderStatus::PATH_NOT_FOUND:
{
StopMovingToPosition();
break;
}
default:
{
}
}
}
}
SetPitchAndYawFromDestination(a_IsFollowingPath);
switch (m_EMState)
{
case IDLE:
{
// If enemy passive we ignore checks for player visibility.
InStateIdle(a_Dt, a_Chunk);
break;
}
case CHASING:
{
// If we do not see a player anymore skip chasing action.
InStateChasing(a_Dt, a_Chunk);
break;
}
case ESCAPING:
{
InStateEscaping(a_Dt, a_Chunk);
break;
}
case ATTACKING: break;
} // switch (m_EMState)
// Leash calculations
CalcLeashActions(a_Dt);
BroadcastMovementUpdate();
// Ambient mob sounds
if (!m_SoundAmbient.empty() && (--m_AmbientSoundTimer <= 0))
{
auto & Random = GetRandomProvider();
auto ShouldPlaySound = Random.RandBool();
if (ShouldPlaySound)
{
auto SoundPitchMultiplier = 1.0f + (Random.RandReal(1.0f) - Random.RandReal(1.0f)) * 0.2f;
m_World->BroadcastSoundEffect(m_SoundAmbient, GetPosition(), 1.0f, SoundPitchMultiplier * 1.0f);
}
m_AmbientSoundTimer = 100;
}
if (m_AgingTimer > 0)
{
m_AgingTimer--;
if ((m_AgingTimer <= 0) && IsBaby())
{
SetAge(1);
m_World->BroadcastEntityMetadata(*this);
}
}
}
void cMonster::CalcLeashActions(std::chrono::milliseconds a_Dt)
{
// This mob just spotted in the world and [m_LeashToPos not null] shows that should be leashed to a leash knot at m_LeashToPos.
// This keeps trying until knot is found. Leash knot may be in a different chunk that needn't or can't be loaded yet.
if (!IsLeashed() && (m_LeashToPos != nullptr))
{
auto LeashKnot = cLeashKnot::FindKnotAtPos(*m_World, { FloorC(m_LeashToPos->x), FloorC(m_LeashToPos->y), FloorC(m_LeashToPos->z) });
if (LeashKnot != nullptr)
{
LeashTo(*LeashKnot);
SetLeashToPos(nullptr);
}
}
if (!IsLeashed())
{
return;
}
static const double CloseFollowDistance = 1.8; // The closest the mob will path towards the leashed to entity
static const double LeashNaturalLength = 5.0; // The closest the mob is actively pulled towards the entity
static const double LeashMaximumLength = 10.0; // Length where the leash breaks
static const double LeashSpringConstant = 20.0; // How stiff the leash is
const auto LeashedToPos = m_LeashedTo->GetPosition();
const auto Displacement = LeashedToPos - GetPosition();
const auto Distance = Displacement.Length();
const auto Direction = Displacement.NormalizeCopy();
// If the leash is over-extended, break the leash:
if (Distance > LeashMaximumLength)
{
LOGD("Leash broken (distance)");
Unleash(false);
return;
}
// If the mob isn't following close enough, pull the mob towards the leashed to entity:
if (Distance > LeashNaturalLength)
{
// Accelerate monster towards the leashed to entity:
const auto Extension = Distance - LeashNaturalLength;
auto Acceleration = Direction * (Extension * LeashSpringConstant);
// Stop mobs from floating up when on the ground
if (IsOnGround() && (Acceleration.y < std::abs(GetGravity())))
{
Acceleration.y = 0.0;
}
// Apply the acceleration
using namespace std::chrono;
AddSpeed(Acceleration * duration_cast<duration<double>>(a_Dt).count());
}
// Passively follow the leashed to entity:
if (Distance > CloseFollowDistance)
{
const Vector3d TargetBlock((LeashedToPos - Direction * CloseFollowDistance).Floor());
// Move to centre of target block face
MoveToPosition(TargetBlock + Vector3d{ 0.5, 0.0, 0.5 });
}
}
void cMonster::SetPitchAndYawFromDestination(bool a_IsFollowingPath)
{
Vector3d BodyDistance;
if (!a_IsFollowingPath)
{
if (GetTarget() == nullptr)
{
// Avoid dirtying head position when nothing will change
// Thus avoids creating unnecessary network traffic
return;
}
BodyDistance = GetTarget()->GetPosition() - GetPosition();
}
else
{
BodyDistance = m_NextWayPointPosition - GetPosition();
}
double BodyRotation, BodyPitch;
BodyDistance.Normalize();
VectorToEuler(BodyDistance.x, BodyDistance.y, BodyDistance.z, BodyRotation, BodyPitch);
SetYaw(BodyRotation);
Vector3d HeadDistance;
if (GetTarget() != nullptr)
{
if (GetTarget()->IsPlayer()) // Look at a player
{
HeadDistance = GetTarget()->GetPosition() - GetPosition();
}
else // Look at some other entity
{
HeadDistance = GetTarget()->GetPosition() - GetPosition();
// HeadDistance.y = GetTarget()->GetPosY() + GetHeight();
}
}
else // Look straight
{
HeadDistance = BodyDistance;
HeadDistance.y = 0;
}
double HeadRotation, HeadPitch;
HeadDistance.Normalize();
VectorToEuler(HeadDistance.x, HeadDistance.y, HeadDistance.z, HeadRotation, HeadPitch);
if ((std::abs(BodyRotation - HeadRotation) < 70) && (std::abs(HeadPitch) < 60))
{
SetHeadYaw(HeadRotation);
SetPitch(-HeadPitch);
}
else
{
SetHeadYaw(BodyRotation);
SetPitch(0);
}
}
void cMonster::HandleFalling()
{
m_bTouchGround = IsOnGround();
Super::HandleFalling();
}
int cMonster::FindFirstNonAirBlockPosition(double a_PosX, double a_PosZ)
{
auto Position = GetPosition().Floor();
Position.y = Clamp(Position.y, 0, cChunkDef::Height);
if (!cBlockInfo::IsSolid(m_World->GetBlock(Position)))
{
while (!cBlockInfo::IsSolid(m_World->GetBlock(Position)) && (Position.y > 0))
{
Position.y--;
}
return Position.y + 1;
}
else
{
while ((Position.y < cChunkDef::Height) && cBlockInfo::IsSolid(m_World->GetBlock(Position)))
{
Position.y++;
}
return Position.y;
}
}
bool cMonster::DoTakeDamage(TakeDamageInfo & a_TDI)
{
if (!Super::DoTakeDamage(a_TDI))
{
return false;
}
if (!m_SoundHurt.empty() && (m_Health > 0))
{
m_World->BroadcastSoundEffect(m_SoundHurt, GetPosition(), 1.0f, 0.8f);
}
if ((a_TDI.Attacker != nullptr) && a_TDI.Attacker->IsPawn())
{
if (
(!a_TDI.Attacker->IsPlayer()) ||
(static_cast<cPlayer *>(a_TDI.Attacker)->CanMobsTarget())
)
{
SetTarget(static_cast<cPawn*>(a_TDI.Attacker));
}
m_TicksSinceLastDamaged = 0;
}
return true;
}
void cMonster::KilledBy(TakeDamageInfo & a_TDI)
{
Super::KilledBy(a_TDI);
if (m_SoundHurt != "")
{
m_World->BroadcastSoundEffect(m_SoundDeath, GetPosition(), 1.0f, 0.8f);
}
if (IsTame())
{
if ((m_MobType == mtWolf) || (m_MobType == mtOcelot) || (m_MobType == mtCat) || (m_MobType == mtParrot))
{
BroadcastDeathMessage(a_TDI);
}
}
int Reward;
switch (m_MobType)
{
// Animals
case mtChicken:
case mtCow:
case mtHorse:
case mtPig:
case mtRabbit:
case mtSheep:
case mtSquid:
case mtMooshroom:
case mtOcelot:
case mtWolf:
{
Reward = GetRandomProvider().RandInt(1, 3);
break;
}
// Monsters
case mtCaveSpider:
case mtCreeper:
case mtEnderman:
case mtGhast:
case mtGuardian:
case mtSilverfish:
case mtSkeleton:
case mtSpider:
case mtWitch:
case mtWitherSkeleton:
case mtZombie:
case mtZombiePigman:
case mtZombieVillager:
case mtSlime:
case mtMagmaCube:
{
Reward = GetRandomProvider().RandInt(6, 8);
break;
}
case mtBlaze:
{
Reward = 10;
break;
}
// Bosses
case mtEnderDragon:
{
Reward = 12000;
break;
}
case mtWither:
{
Reward = 50;
break;
}
default:
{
Reward = 0;
break;
}
}
if ((a_TDI.Attacker != nullptr) && (!IsBaby()))
{
m_World->SpawnSplitExperienceOrbs(GetPosX(), GetPosY(), GetPosZ(), Reward);
}
m_DestroyTimer = std::chrono::milliseconds(0);
}
void cMonster::OnRightClicked(cPlayer & a_Player)
{
Super::OnRightClicked(a_Player);
const cItem & EquippedItem = a_Player.GetEquippedItem();
if ((EquippedItem.m_ItemType == E_ITEM_NAME_TAG) && !EquippedItem.m_CustomName.empty())
{
SetCustomName(EquippedItem.m_CustomName);
if (!a_Player.IsGameModeCreative())
{
a_Player.GetInventory().RemoveOneEquippedItem();
}
}
// Using leashes
m_IsLeashActionJustDone = false;
if (IsLeashed() && (GetLeashedTo() == &a_Player)) // a player can only unleash a mob leashed to him
{
Unleash(!a_Player.IsGameModeCreative());
}
else if (IsLeashed())
{
// Mob is already leashed but client anticipates the server action and draws a leash link, so we need to send current leash to cancel it
m_World->BroadcastLeashEntity(*this, *this->GetLeashedTo());
}
else if (CanBeLeashed() && (EquippedItem.m_ItemType == E_ITEM_LEASH))
{
if (!a_Player.IsGameModeCreative())
{
a_Player.GetInventory().RemoveOneEquippedItem();
}
LeashTo(a_Player);
}
}
// Checks to see if EventSeePlayer should be fired
// monster sez: Do I see the player
void cMonster::CheckEventSeePlayer(cChunk & a_Chunk)
{
if (GetTarget() != nullptr)
{
return;
}
cPlayer * TargetPlayer = nullptr;
double ClosestDistance = m_SightDistance * m_SightDistance;
const auto MyHeadPosition = GetPosition().addedY(GetHeight());
// Enumerate all players within sight:
m_World->ForEachPlayer([this, &TargetPlayer, &ClosestDistance, MyHeadPosition](cPlayer & a_Player)
{
if (!a_Player.CanMobsTarget())
{
return false;
}
const auto TargetHeadPosition = a_Player.GetPosition().addedY(a_Player.GetHeight());
const auto TargetDistance = (TargetHeadPosition - MyHeadPosition).SqrLength();
// TODO: Currently all mobs see through lava, but only Nether-native mobs should be able to.
if (
(TargetDistance < ClosestDistance) &&
cLineBlockTracer::LineOfSightTrace(*GetWorld(), MyHeadPosition, TargetHeadPosition, cLineBlockTracer::losAirWaterLava)
)
{
TargetPlayer = &a_Player;
ClosestDistance = TargetDistance;
}
return false;
});
// Target him if suitable player found:
if (TargetPlayer != nullptr)
{
EventSeePlayer(TargetPlayer, a_Chunk);
}
}
void cMonster::CheckEventLostPlayer(const std::chrono::milliseconds a_Dt)
{
const auto Target = GetTarget();
if (Target == nullptr)
{
return;
}
// Check if the player died, is in creative mode, etc:
if (Target->IsPlayer() && !static_cast<cPlayer *>(Target)->CanMobsTarget())
{
EventLosePlayer();
return;
}
// Check if the target is too far away:
if (!Target->GetBoundingBox().DoesIntersect({ GetPosition(), m_SightDistance * 2.0 }))
{
EventLosePlayer();
return;
}
const auto MyHeadPosition = GetPosition().addedY(GetHeight());
const auto TargetHeadPosition = Target->GetPosition().addedY(Target->GetHeight());
if (!cLineBlockTracer::LineOfSightTrace(*GetWorld(), MyHeadPosition, TargetHeadPosition, cLineBlockTracer::losAirWaterLava))
{
if ((m_LoseSightAbandonTargetTimer += a_Dt) > std::chrono::seconds(4))
{
EventLosePlayer();
}
}
else
{
// Subtract the amount of time we "handled" instead of setting to zero, so we don't ignore a large a_Dt of say, 8s:
m_LoseSightAbandonTargetTimer -= std::min(std::chrono::milliseconds(4000), m_LoseSightAbandonTargetTimer);
}
}
// What to do if player is seen
// default to change state to chasing
void cMonster::EventSeePlayer(cPlayer * a_SeenPlayer, cChunk & a_Chunk)
{
UNUSED(a_Chunk);
SetTarget(a_SeenPlayer);
}
void cMonster::EventLosePlayer(void)
{
SetTarget(nullptr);
m_EMState = IDLE;
m_LoseSightAbandonTargetTimer = std::chrono::seconds::zero();
}
void cMonster::InStateIdle(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
{
if (m_PathfinderActivated)
{
return; // Still getting there
}
m_IdleInterval += a_Dt;
if (m_IdleInterval > std::chrono::seconds(1))
{
auto & Random = GetRandomProvider();
// At this interval the results are predictable
int rem = Random.RandInt(1, 7);
m_IdleInterval -= std::chrono::seconds(1); // So nothing gets dropped when the server hangs for a few seconds
Vector3d Dist;
Dist.x = static_cast<double>(Random.RandInt(-5, 5));
Dist.z = static_cast<double>(Random.RandInt(-5, 5));
if ((Dist.SqrLength() > 2) && (rem >= 3))
{
Vector3d Destination(GetPosX() + Dist.x, GetPosition().y, GetPosZ() + Dist.z);
cChunk * Chunk = a_Chunk.GetNeighborChunk(static_cast<int>(Destination.x), static_cast<int>(Destination.z));
if ((Chunk == nullptr) || !Chunk->IsValid())
{
return;
}
BLOCKTYPE BlockType;
NIBBLETYPE BlockMeta;
int RelX = static_cast<int>(Destination.x) - Chunk->GetPosX() * cChunkDef::Width;
int RelZ = static_cast<int>(Destination.z) - Chunk->GetPosZ() * cChunkDef::Width;
int YBelowUs = static_cast<int>(Destination.y) - 1;
if (YBelowUs >= 0)
{
Chunk->GetBlockTypeMeta(RelX, YBelowUs, RelZ, BlockType, BlockMeta);
if (BlockType != E_BLOCK_STATIONARY_WATER) // Idle mobs shouldn't enter water on purpose
{
MoveToPosition(Destination);
}
}
}
}
}
// What to do if in Chasing State
// This state should always be defined in each child class
void cMonster::InStateChasing(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
{
UNUSED(a_Dt);
}
// What to do if in Escaping State
void cMonster::InStateEscaping(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
{
UNUSED(a_Dt);
if (GetTarget() != nullptr)
{
Vector3d newloc = GetPosition();
newloc.x = (GetTarget()->GetPosition().x < newloc.x)? (newloc.x + m_SightDistance): (newloc.x - m_SightDistance);
newloc.z = (GetTarget()->GetPosition().z < newloc.z)? (newloc.z + m_SightDistance): (newloc.z - m_SightDistance);
MoveToPosition(newloc);
}
else
{
m_EMState = IDLE; // This shouldnt be required but just to be safe
}
}
void cMonster::ResetAttackCooldown()
{
m_AttackCoolDownTicksLeft = static_cast<int>(TPS * m_AttackRate); // A second has 20 ticks, an attack rate of 1 means 1 hit every second
}
void cMonster::SetCustomName(const AString & a_CustomName)
{
m_CustomName = a_CustomName;
// The maximal length is 64
if (a_CustomName.length() > 64)
{
m_CustomName = a_CustomName.substr(0, 64);
}
if (m_World != nullptr)
{
m_World->BroadcastEntityMetadata(*this);
}
}
void cMonster::SetCustomNameAlwaysVisible(bool a_CustomNameAlwaysVisible)
{
m_CustomNameAlwaysVisible = a_CustomNameAlwaysVisible;
if (m_World != nullptr)
{
m_World->BroadcastEntityMetadata(*this);
}
}
void cMonster::GetMonsterConfig(const AString & a_Name)
{
cRoot::Get()->GetMonsterConfig()->AssignAttributes(this, a_Name);
}
bool cMonster::IsNetherNative(void)
{
return false;
}
bool cMonster::IsUndead(void)
{
return false;
}
AString cMonster::MobTypeToString(eMonsterType a_MobType)
{
// Mob types aren't sorted, so we need to search linearly:
for (size_t i = 0; i < ARRAYCOUNT(g_MobTypeNames); i++)
{
if (g_MobTypeNames[i].m_Type == a_MobType)
{
return g_MobTypeNames[i].m_lcName;
}
}
// Not found:
return "";
}
AString cMonster::MobTypeToVanillaName(eMonsterType a_MobType)
{
// Mob types aren't sorted, so we need to search linearly:
for (size_t i = 0; i < ARRAYCOUNT(g_MobTypeNames); i++)
{
if (g_MobTypeNames[i].m_Type == a_MobType)
{
return g_MobTypeNames[i].m_VanillaName;
}
}
// Not found:
return "";
}
AString cMonster::MobTypeToVanillaNBT(eMonsterType a_MobType)
{
// Mob types aren't sorted, so we need to search linearly:
for (size_t i = 0; i < ARRAYCOUNT(g_MobTypeNames); i++)
{
if (g_MobTypeNames[i].m_Type == a_MobType)
{
return g_MobTypeNames[i].m_VanillaNameNBT;
}
}
// Not found:
return "";
}
eMonsterType cMonster::StringToMobType(const AString & a_Name)
{
AString lcName = StrToLower(a_Name);
// Search Cuberite name:
for (size_t i = 0; i < ARRAYCOUNT(g_MobTypeNames); i++)
{
if (strcmp(g_MobTypeNames[i].m_lcName, lcName.c_str()) == 0)
{
return g_MobTypeNames[i].m_Type;
}
}
// Not found. Search Vanilla name:
for (size_t i = 0; i < ARRAYCOUNT(g_MobTypeNames); i++)
{
if (strcmp(StrToLower(g_MobTypeNames[i].m_VanillaName).c_str(), lcName.c_str()) == 0)
{
return g_MobTypeNames[i].m_Type;
}
}
// Search in NBT name
for (size_t i = 0; i < ARRAYCOUNT(g_MobTypeNames); i++)
{
if (strcmp(StrToLower(g_MobTypeNames[i].m_VanillaNameNBT).c_str(), lcName.c_str()) == 0)
{
return g_MobTypeNames[i].m_Type;
}
}
// Not found:
return mtInvalidType;
}
cMonster::eFamily cMonster::FamilyFromType(eMonsterType a_Type)
{
// Passive-agressive mobs are counted in mob spawning code as passive
switch (a_Type)
{
case mtBat: return mfAmbient;
case mtBlaze: return mfHostile;
case mtCat: return mfPassive;
case mtCaveSpider: return mfHostile;
case mtChicken: return mfPassive;
case mtCod: return mfWater;
case mtCow: return mfPassive;
case mtCreeper: return mfHostile;
case mtDolphin: return mfWater;
case mtDonkey: return mfPassive;
case mtDrowned: return mfHostile;
case mtElderGuardian: return mfHostile;
case mtEnderDragon: return mfNoSpawn;
case mtEnderman: return mfHostile;
case mtEndermite: return mfHostile;
case mtEvoker: return mfHostile;
case mtFox: return mfPassive;
case mtGhast: return mfHostile;
case mtGiant: return mfNoSpawn;
case mtGuardian: return mfWater; // Just because they have special spawning conditions. TODO: If Watertemples have been added, this needs to be edited!
case mtHoglin: return mfHostile;
case mtHorse: return mfPassive;
case mtHusk: return mfHostile;
case mtIllusioner: return mfHostile;
case mtIronGolem: return mfPassive;
case mtLlama: return mfPassive;
case mtMagmaCube: return mfHostile;
case mtMooshroom: return mfPassive;
case mtMule: return mfPassive;
case mtOcelot: return mfPassive;
case mtPanda: return mfPassive;
case mtParrot: return mfPassive;
case mtPhantom: return mfHostile;
case mtPig: return mfPassive;
case mtPiglin: return mfHostile;
case mtPiglinBrute: return mfHostile;
case mtPillager: return mfHostile;
case mtPolarBear: return mfPassive;
case mtPufferfish: return mfWater;
case mtRabbit: return mfPassive;
case mtRavager: return mfHostile;
case mtSalmon: return mfWater;
case mtSheep: return mfPassive;
case mtShulker: return mfHostile;
case mtSilverfish: return mfHostile;
case mtSkeleton: return mfHostile;
case mtSkeletonHorse: return mfPassive;
case mtSlime: return mfHostile;
case mtSnowGolem: return mfNoSpawn;
case mtSpider: return mfHostile;
case mtSquid: return mfWater;
case mtStray: return mfHostile;
case mtStrider: return mfHostile;
case mtTraderLlama: return mfPassive;
case mtTropicalFish: return mfWater;
case mtTurtle: return mfWater; // I'm not quite sure
case mtVex: return mfHostile;
case mtVindicator: return mfHostile;
case mtVillager: return mfPassive;
case mtWanderingTrader: return mfPassive;
case mtWitch: return mfHostile;
case mtWither: return mfNoSpawn;
case mtWitherSkeleton: return mfHostile;
case mtWolf: return mfPassive;
case mtZoglin: return mfHostile;
case mtZombie: return mfHostile;
case mtZombieHorse: return mfPassive;
case mtZombiePigman: return mfHostile;
case mtZombieVillager: return mfHostile;
case mtInvalidType: break;
}
UNREACHABLE("Unhandled mob type");
}
cTickTime cMonster::GetSpawnDelay(cMonster::eFamily a_MobFamily)
{
switch (a_MobFamily)
{
case mfHostile: return 40_tick;
case mfPassive: return 40_tick;
case mfAmbient: return 40_tick;
case mfWater: return 400_tick;
case mfNoSpawn: return -1_tick;
}
UNREACHABLE("Unhandled mob family");
}
/** Sets the target. */
void cMonster::SetTarget (cPawn * a_NewTarget)
{
ASSERT((a_NewTarget == nullptr) || (IsTicking()));
if (m_Target == a_NewTarget)
{
return;
}
cPawn * OldTarget = m_Target;
m_Target = a_NewTarget;
if (OldTarget != nullptr)
{
// Notify the old target that we are no longer targeting it.
OldTarget->NoLongerTargetingMe(this);
}
if (a_NewTarget != nullptr)
{
ASSERT(a_NewTarget->IsTicking());
// Notify the new target that we are now targeting it.
m_Target->TargetingMe(this);
m_WasLastTargetAPlayer = m_Target->IsPlayer();
}
}
void cMonster::UnsafeUnsetTarget()
{
m_Target = nullptr;
}
cPawn * cMonster::GetTarget()
{
return m_Target;
}
std::unique_ptr<cMonster> cMonster::NewMonsterFromType(eMonsterType a_MobType)
{
auto & Random = GetRandomProvider();
// Create the mob entity
switch (a_MobType)
{
case mtMagmaCube:
{
return std::make_unique<cMagmaCube>(1 << Random.RandInt(2)); // Size 1, 2 or 4
}
case mtSlime:
{
return std::make_unique<cSlime>(1 << Random.RandInt(2)); // Size 1, 2 or 4
}
case mtVillager: return std::make_unique<cVillager>(cVillager::GetRandomProfession());
case mtHorse:
{
// Horses take a type (species), a colour, and a style (dots, stripes, etc.)
int HorseType = Random.RandInt(7);
int HorseColor = Random.RandInt(6);
int HorseStyle = Random.RandInt(4);
int HorseTameTimes = Random.RandInt(1, 6);
if ((HorseType == 5) || (HorseType == 6) || (HorseType == 7))
{
// Increase chances of normal horse (zero)
HorseType = 0;
}
return std::make_unique<cHorse>(HorseType, HorseColor, HorseStyle, HorseTameTimes);
}
case mtZombieVillager:
{
return std::make_unique<cZombieVillager>(cVillager::GetRandomProfession());
}
case mtBat: return std::make_unique<cBat>();
case mtBlaze: return std::make_unique<cBlaze>();
case mtCaveSpider: return std::make_unique<cCaveSpider>();
case mtChicken: return std::make_unique<cChicken>();
case mtCow: return std::make_unique<cCow>();
case mtCreeper: return std::make_unique<cCreeper>();
case mtEnderDragon: return std::make_unique<cEnderDragon>();
case mtEnderman: return std::make_unique<cEnderman>();
case mtGhast: return std::make_unique<cGhast>();
case mtGiant: return std::make_unique<cGiant>();
case mtGuardian: return std::make_unique<cGuardian>();
case mtIronGolem: return std::make_unique<cIronGolem>();
case mtMooshroom: return std::make_unique<cMooshroom>();
case mtOcelot: return std::make_unique<cOcelot>();
case mtPig: return std::make_unique<cPig>();
case mtRabbit: return std::make_unique<cRabbit>();
case mtSheep: return std::make_unique<cSheep>();
case mtSilverfish: return std::make_unique<cSilverfish>();
case mtSkeleton: return std::make_unique<cSkeleton>();
case mtSnowGolem: return std::make_unique<cSnowGolem>();
case mtSpider: return std::make_unique<cSpider>();
case mtSquid: return std::make_unique<cSquid>();
case mtWitch: return std::make_unique<cWitch>();
case mtWither: return std::make_unique<cWither>();
case mtWitherSkeleton: return std::make_unique<cWitherSkeleton>();
case mtWolf: return std::make_unique<cWolf>();
case mtZombie: return std::make_unique<cZombie>();
case mtZombiePigman: return std::make_unique<cZombiePigman>();
default:
{
ASSERT(!"Unhandled mob type whilst trying to spawn mob!");
return nullptr;
}
}
}
void cMonster::EngageLoveMode(cMonster *a_Partner)
{
m_LovePartner = a_Partner;
m_MatingTimer = 50; // about 3 seconds of mating
}
void cMonster::ResetLoveMode()
{
m_LovePartner = nullptr;
m_LoveTimer = 0;
m_MatingTimer = 0;
m_LoveCooldown = TPS * 60 * 5; // 5 minutes
// when an animal is in love mode, the client only stops sending the hearts if we let them know it's in cooldown, which is done with the "age" metadata
m_World->BroadcastEntityMetadata(*this);
}
void cMonster::LoveTick(void)
{
// if we have a partner, mate
if (m_LovePartner != nullptr)
{
if (m_MatingTimer > 0)
{
// If we should still mate, keep bumping into them until baby is made
Vector3d Pos = m_LovePartner->GetPosition();
MoveToPosition(Pos);
}
else
{
// Mating finished. Spawn baby
Vector3f Pos = (GetPosition() + m_LovePartner->GetPosition()) * 0.5;
UInt32 BabyID = m_World->SpawnMob(Pos.x, Pos.y, Pos.z, GetMobType(), true);
cMonster * Baby = nullptr;
m_World->DoWithEntityByID(BabyID, [&](cEntity & a_Entity)
{
Baby = static_cast<cMonster *>(&a_Entity);
return true;
});
if (Baby != nullptr)
{
Baby->InheritFromParents(this, m_LovePartner);
}
m_World->SpawnExperienceOrb(Pos.x, Pos.y, Pos.z, GetRandomProvider().RandInt(1, 6));
m_World->DoWithPlayerByUUID(m_Feeder, [&] (cPlayer & a_Player)
{
a_Player.GetStatistics().Custom[CustomStatistic::AnimalsBred]++;
if (GetMobType() == eMonsterType::mtCow)
{
a_Player.AwardAchievement(CustomStatistic::AchBreedCow);
}
return true;
});
m_LovePartner->ResetLoveMode();
ResetLoveMode();
}
}
else
{
// We have no partner, so we just chase the player if they have our breeding item
cItems FollowedItems;
GetFollowedItems(FollowedItems);
if (FollowedItems.Size() > 0)
{
m_World->DoWithNearestPlayer(GetPosition(), static_cast<float>(m_SightDistance), [&](cPlayer & a_Player) -> bool
{
const cItem & EquippedItem = a_Player.GetEquippedItem();
if (FollowedItems.ContainsType(EquippedItem))
{
Vector3d PlayerPos = a_Player.GetPosition();
MoveToPosition(PlayerPos);
}
return true;
});
}
}
// If we are in love mode but we have no partner, search for a partner neabry
if (m_LoveTimer > 0)
{
if (m_LovePartner == nullptr)
{
m_World->ForEachEntityInBox(cBoundingBox(GetPosition(), 8, 8), [=](cEntity & a_Entity)
{
// If the entity is not a monster, don't breed with it
// Also, do not self-breed
if ((a_Entity.GetEntityType() != etMonster) || (&a_Entity == this))
{
return false;
}
auto & Me = static_cast<cMonster &>(*this);
auto & PotentialPartner = static_cast<cMonster &>(a_Entity);
// If the potential partner is not of the same species, don't breed with it
if (PotentialPartner.GetMobType() != Me.GetMobType())
{
return false;
}
// If the potential partner is not in love
// Or they already have a mate, do not breed with them
if ((!PotentialPartner.IsInLove()) || (PotentialPartner.GetPartner() != nullptr))
{
return false;
}
// All conditions met, let's breed!
PotentialPartner.EngageLoveMode(&Me);
Me.EngageLoveMode(&PotentialPartner);
return true;
});
}
m_LoveTimer--;
}
if (m_MatingTimer > 0)
{
m_MatingTimer--;
}
if (m_LoveCooldown > 0)
{
m_LoveCooldown--;
}
}
void cMonster::RightClickFeed(cPlayer & a_Player)
{
const cItem & EquippedItem = a_Player.GetEquippedItem();
// If a player holding breeding items right-clicked me, go into love mode
if ((m_LoveCooldown == 0) && !IsInLove() && !IsBaby())
{
cItems Items;
GetBreedingItems(Items);
if (Items.ContainsType(EquippedItem.m_ItemType))
{
if (!a_Player.IsGameModeCreative())
{
a_Player.GetInventory().RemoveOneEquippedItem();
}
m_LoveTimer = TPS * 30; // half a minute
m_World->BroadcastEntityAnimation(*this, EntityAnimation::AnimalFallsInLove);
}
}
// If a player holding my spawn egg right-clicked me, spawn a new baby
if (EquippedItem.m_ItemType == E_ITEM_SPAWN_EGG)
{
eMonsterType MonsterType = cItemSpawnEggHandler::ItemDamageToMonsterType(EquippedItem.m_ItemDamage);
if (
(MonsterType == m_MobType) &&
(m_World->SpawnMob(GetPosX(), GetPosY(), GetPosZ(), m_MobType, true) != cEntity::INVALID_ID) // Spawning succeeded
)
{
if (!a_Player.IsGameModeCreative())
{
// The mob was spawned, "use" the item:
a_Player.GetInventory().RemoveOneEquippedItem();
}
}
}
// Stores feeder UUID for statistic tracking
m_Feeder = a_Player.GetUUID();
}
void cMonster::AddRandomDropItem(cItems & a_Drops, unsigned int a_Min, unsigned int a_Max, short a_Item, short a_ItemHealth)
{
auto Count = GetRandomProvider().RandInt<unsigned int>(a_Min, a_Max);
auto MaxStackSize = static_cast<unsigned char>(cItem(a_Item).GetMaxStackSize());
while (Count > MaxStackSize)
{
a_Drops.emplace_back(a_Item, MaxStackSize, a_ItemHealth);
Count -= MaxStackSize;
}
if (Count > 0)
{
a_Drops.emplace_back(a_Item, Count, a_ItemHealth);
}
}
void cMonster::AddRandomUncommonDropItem(cItems & a_Drops, float a_Chance, short a_Item, short a_ItemHealth)
{
if (GetRandomProvider().RandBool(a_Chance / 100.0))
{
a_Drops.emplace_back(a_Item, 1, a_ItemHealth);
}
}
void cMonster::AddRandomRareDropItem(cItems & a_Drops, cItems & a_Items, unsigned int a_LootingLevel)
{
auto & r1 = GetRandomProvider();
if (r1.RandBool((5 + a_LootingLevel) / 200.0))
{
size_t Rare = r1.RandInt<size_t>(a_Items.Size() - 1);
a_Drops.push_back(a_Items.at(Rare));
}
}
void cMonster::AddRandomArmorDropItem(cItems & a_Drops, unsigned int a_LootingLevel)
{
auto & r1 = GetRandomProvider();
double LootingBonus = a_LootingLevel / 100.0;
if (r1.RandBool(m_DropChanceHelmet + LootingBonus))
{
if (!GetEquippedHelmet().IsEmpty())
{
a_Drops.push_back(GetEquippedHelmet());
}
}
if (r1.RandBool(m_DropChanceChestplate + LootingBonus))
{
if (!GetEquippedChestplate().IsEmpty())
{
a_Drops.push_back(GetEquippedChestplate());
}
}
if (r1.RandBool(m_DropChanceLeggings + LootingBonus))
{
if (!GetEquippedLeggings().IsEmpty())
{
a_Drops.push_back(GetEquippedLeggings());
}
}
if (r1.RandBool(m_DropChanceBoots + LootingBonus))
{
if (!GetEquippedBoots().IsEmpty())
{
a_Drops.push_back(GetEquippedBoots());
}
}
}
void cMonster::AddRandomWeaponDropItem(cItems & a_Drops, unsigned int a_LootingLevel)
{
if (GetRandomProvider().RandBool(m_DropChanceWeapon + (a_LootingLevel / 100.0)))
{
if (!GetEquippedWeapon().IsEmpty())
{
a_Drops.push_back(GetEquippedWeapon());
}
}
}
void cMonster::HandleDaylightBurning(cChunk & a_Chunk, bool WouldBurn)
{
if (!m_BurnsInDaylight)
{
return;
}
int RelY = POSY_TOINT;
if ((RelY < 0) || (RelY >= cChunkDef::Height))
{
// Outside the world
return;
}
if (!a_Chunk.IsLightValid())
{
m_World->QueueLightChunk(GetChunkX(), GetChunkZ());
return;
}
if (!IsOnFire() && WouldBurn)
{
// Burn for 100 ticks, then decide again
StartBurning(100);
}
}
bool cMonster::WouldBurnAt(Vector3d a_Location, cChunk & a_Chunk)
{
// If the Y coord is out of range, return the most logical result without considering anything else:
int RelY = FloorC(a_Location.y);
if (RelY >= cChunkDef::Height)
{
// Always burn above the world
return true;
}
if (RelY <= 0)
{
// The mob is about to die, no point in burning
return false;
}
PREPARE_REL_AND_CHUNK(a_Location, a_Chunk);
if (!RelSuccess)
{
return false;
}
if (
(Chunk->GetBlock(Rel) != E_BLOCK_SOULSAND) && // Not on soulsand
(GetWorld()->GetTimeOfDay() < 13000_tick) && // Daytime
Chunk->IsWeatherSunnyAt(Rel.x, Rel.z) && // Not raining
!IsInWater() // Isn't swimming
)
{
int MobHeight = CeilC(a_Location.y + GetHeight()) - 1; // The block Y coord of the mob's head
if (MobHeight >= cChunkDef::Height)
{
return true;
}
// Start with the highest block and scan down to just above the mob's head.
// If a non transparent is found, return false (do not burn). Otherwise return true.
// Note that this loop is not a performance concern as transparent blocks are rare and the loop almost always bailes out
// instantly.(An exception is e.g. standing under a long column of glass).
int CurrentBlock = Chunk->GetHeight(Rel.x, Rel.z);
while (CurrentBlock > MobHeight)
{
BLOCKTYPE Block = Chunk->GetBlock(Rel.x, CurrentBlock, Rel.z);
if (
// Do not burn if a block above us meets one of the following conditions:
(!cBlockInfo::IsTransparent(Block)) ||
(Block == E_BLOCK_LEAVES) ||
(Block == E_BLOCK_NEW_LEAVES) ||
(IsBlockWater(Block))
)
{
return false;
}
--CurrentBlock;
}
return true;
}
return false;
}
cMonster::eFamily cMonster::GetMobFamily(void) const
{
return FamilyFromType(m_MobType);
}
void cMonster::LeashTo(cEntity & a_Entity, bool a_ShouldBroadcast)
{
// Do nothing if already leashed
if (m_LeashedTo != nullptr)
{
return;
}
m_LeashedTo = &a_Entity;
a_Entity.AddLeashedMob(this);
if (a_ShouldBroadcast)
{
m_World->BroadcastLeashEntity(*this, a_Entity);
}
m_IsLeashActionJustDone = true;
}
void cMonster::Unleash(bool a_ShouldDropLeashPickup, bool a_ShouldBroadcast)
{
// Do nothing if not leashed
if (m_LeashedTo == nullptr)
{
return;
}
m_LeashedTo->RemoveLeashedMob(this);
m_LeashedTo = nullptr;
if (a_ShouldDropLeashPickup)
{
cItems Pickups;
Pickups.Add(cItem(E_ITEM_LEASH, 1, 0));
GetWorld()->SpawnItemPickups(Pickups, GetPosX() + 0.5, GetPosY() + 0.5, GetPosZ() + 0.5);
}
if (a_ShouldBroadcast)
{
m_World->BroadcastUnleashEntity(*this);
}
m_IsLeashActionJustDone = true;
}
void cMonster::Unleash(bool a_ShouldDropLeashPickup)
{
Unleash(a_ShouldDropLeashPickup, true);
}
|