-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathAutomobileEntity.java
1733 lines (1468 loc) · 70.5 KB
/
AutomobileEntity.java
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
package io.github.foundationgames.automobility.entity;
import io.github.foundationgames.automobility.Automobility;
import io.github.foundationgames.automobility.automobile.AutomobileEngine;
import io.github.foundationgames.automobility.automobile.AutomobileFrame;
import io.github.foundationgames.automobility.automobile.AutomobileStats;
import io.github.foundationgames.automobility.automobile.AutomobileWheel;
import io.github.foundationgames.automobility.automobile.WheelBase;
import io.github.foundationgames.automobility.automobile.attachment.FrontAttachmentType;
import io.github.foundationgames.automobility.automobile.attachment.RearAttachmentType;
import io.github.foundationgames.automobility.automobile.attachment.front.FrontAttachment;
import io.github.foundationgames.automobility.automobile.attachment.rear.DeployableRearAttachment;
import io.github.foundationgames.automobility.automobile.attachment.rear.RearAttachment;
import io.github.foundationgames.automobility.automobile.render.RenderableAutomobile;
import io.github.foundationgames.automobility.block.AutomobileAssemblerBlock;
import io.github.foundationgames.automobility.block.LaunchGelBlock;
import io.github.foundationgames.automobility.block.OffRoadBlock;
import io.github.foundationgames.automobility.controller.AutomobileController;
import io.github.foundationgames.automobility.item.AutomobileInteractable;
import io.github.foundationgames.automobility.item.AutomobilityItems;
import io.github.foundationgames.automobility.particle.AutomobilityParticles;
import io.github.foundationgames.automobility.platform.Platform;
import io.github.foundationgames.automobility.screen.AutomobileContainerLevelAccess;
import io.github.foundationgames.automobility.sound.AutomobilitySounds;
import io.github.foundationgames.automobility.util.AUtils;
import io.github.foundationgames.automobility.util.duck.CollisionArea;
import io.github.foundationgames.automobility.util.network.ClientPackets;
import io.github.foundationgames.automobility.util.network.CommonPackets;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Cursor3D;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.ClientGamePacketListener;
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.syncher.EntityDataSerializers;
import net.minecraft.network.syncher.SynchedEntityData;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.Mth;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntitySelector;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.Mob;
import net.minecraft.world.entity.MoverType;
import net.minecraft.world.entity.animal.WaterAnimal;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.vehicle.Boat;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.entity.EntityTypeTest;
import net.minecraft.world.level.gameevent.GameEvent;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.phys.shapes.BooleanOp;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.Shapes;
import org.jetbrains.annotations.Nullable;
import org.joml.Vector3f;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;
public class AutomobileEntity extends Entity implements RenderableAutomobile, EntityWithInventory {
public static Consumer<AutomobileEntity> engineSound = e -> {};
public static Consumer<AutomobileEntity> skidSound = e -> {};
private static final EntityDataAccessor<Float> REAR_ATTACHMENT_YAW = SynchedEntityData.defineId(AutomobileEntity.class, EntityDataSerializers.FLOAT);
private static final EntityDataAccessor<Float> REAR_ATTACHMENT_ANIMATION = SynchedEntityData.defineId(AutomobileEntity.class, EntityDataSerializers.FLOAT);
private static final EntityDataAccessor<Float> FRONT_ATTACHMENT_ANIMATION = SynchedEntityData.defineId(AutomobileEntity.class, EntityDataSerializers.FLOAT);
private AutomobileFrame frame = AutomobileFrame.REGISTRY.getOrDefault(null);
private AutomobileWheel wheels = AutomobileWheel.REGISTRY.getOrDefault(null);
private AutomobileEngine engine = AutomobileEngine.REGISTRY.getOrDefault(null);
private RearAttachment rearAttachment;
private FrontAttachment frontAttachment;
private final AutomobileStats stats = new AutomobileStats();
public static final int SMALL_TURBO_TIME = 35;
public static final int MEDIUM_TURBO_TIME = 70;
public static final int LARGE_TURBO_TIME = 115;
public static final float TERMINAL_VELOCITY = -1.2f;
private long clientTime;
private double trackedX;
private double trackedY;
private double trackedZ;
private float trackedYaw;
private int lerpTicks;
private boolean dirty = false;
private float engineSpeed = 0;
private float boostSpeed = 0;
private float speedDirection = 0;
private float lastBoostSpeed = boostSpeed;
private int boostTimer = 0;
private float boostPower = 0;
private int jumpCooldown = 0;
private float hSpeed = 0;
private float vSpeed = 0;
private Vec3 addedVelocity = getDeltaMovement();
private float steering = 0;
private float lastSteering = steering;
private float angularSpeed = 0;
private float wheelAngle = 0;
private float lastWheelAngle = 0;
private final Displacement displacement = new AutomobileEntity.Displacement();
private boolean drifting = false;
private boolean burningOut = false;
private int driftDir = 0;
private float turboCharge = 0;
private float lockedViewOffset = 0;
private boolean automobileOnGround = true;
private boolean wasOnGround = automobileOnGround;
private boolean isFloorDirectlyBelow = true;
private boolean touchingWall = false;
private Vec3 lastVelocity = Vec3.ZERO;
private Vec3 lastPosForDisplacement = Vec3.ZERO;
private Vec3 prevTailPos = null;
private int slopeStickingTimer = 0;
private float grip = 1;
private int suspensionBounceTimer = 0;
private int lastSusBounceTimer = suspensionBounceTimer;
private final Deque<Double> prevYDisplacements = new ArrayDeque<>();
private boolean offRoad = false;
private Vector3f debrisColor = new Vector3f();
private int fallTicks = 0;
private int despawnTime = -1;
private int despawnCountdown = 0;
private boolean decorative = false;
private boolean wasEngineRunning = false;
private float standStillTime = -1.3f;
public void writeSyncToClientData(FriendlyByteBuf buf) {
buf.writeInt(boostTimer);
buf.writeFloat(steering);
buf.writeFloat(wheelAngle);
buf.writeFloat(turboCharge);
buf.writeFloat(engineSpeed);
buf.writeFloat(boostSpeed);
buf.writeByte(compactInputData());
buf.writeBoolean(drifting);
buf.writeBoolean(burningOut);
}
public void readSyncToClientData(FriendlyByteBuf buf) {
boostTimer = buf.readInt();
steering = buf.readFloat();
wheelAngle = buf.readFloat();
turboCharge = buf.readFloat();
engineSpeed = buf.readFloat();
boostSpeed = buf.readFloat();
// TODO: compact floats into bytes making one integer maybe?
readCompactedInputData(buf.readByte());
setDrifting(buf.readBoolean());
setBurningOut(buf.readBoolean());
}
@Override
public void readAdditionalSaveData(CompoundTag nbt) {
setComponents(
AutomobileFrame.REGISTRY.getOrDefault(ResourceLocation.tryParse(nbt.getString("frame"))),
AutomobileWheel.REGISTRY.getOrDefault(ResourceLocation.tryParse(nbt.getString("wheels"))),
AutomobileEngine.REGISTRY.getOrDefault(ResourceLocation.tryParse(nbt.getString("engine")))
);
var rAtt = nbt.getCompound("rearAttachment");
setRearAttachment(RearAttachment.fromNbt(rAtt));
rearAttachment.readNbt(rAtt);
var fAtt = nbt.getCompound("frontAttachment");
setFrontAttachment(FrontAttachment.fromNbt(fAtt));
frontAttachment.readNbt(fAtt);
engineSpeed = nbt.getFloat("engineSpeed");
boostSpeed = nbt.getFloat("boostSpeed");
boostTimer = nbt.getInt("boostTimer");
boostPower = nbt.getFloat("boostPower");
speedDirection = nbt.getFloat("speedDirection");
vSpeed = nbt.getFloat("verticalSpeed");
hSpeed = nbt.getFloat("horizontalSpeed");
addedVelocity = AUtils.v3dFromNbt(nbt.getCompound("addedVelocity"));
lastVelocity = AUtils.v3dFromNbt(nbt.getCompound("lastVelocity"));
angularSpeed = nbt.getFloat("angularSpeed");
steering = nbt.getFloat("steering");
wheelAngle = nbt.getFloat("wheelAngle");
drifting = nbt.getBoolean("drifting");
driftDir = nbt.getInt("driftDir");
burningOut = nbt.getBoolean("burningOut");
turboCharge = nbt.getInt("turboCharge");
// backwards compatibility
if (nbt.contains("accelerating")) {
acceleration = nbt.getBoolean("accelerating") ? 1f : 0f;
brakeForce = nbt.getBoolean("braking") ? 1f : 0f;
steerLeftImpulse = nbt.getBoolean("steeringLeft") ? 1f : nbt.getBoolean("steeringRight") ? -1f : 0f;
} else {
acceleration = nbt.getFloat("acceleration");
brakeForce = nbt.getFloat("brakeForce");
steerLeftImpulse = nbt.getFloat("steerLeftImpulse");
}
holdingDrift = nbt.getBoolean("holdingDrift");
fallTicks = nbt.getInt("fallTicks");
despawnTime = nbt.getInt("despawnTime");
despawnCountdown = nbt.getInt("despawnCountdown");
decorative = nbt.getBoolean("decorative");
}
@Override
public void addAdditionalSaveData(CompoundTag nbt) {
nbt.putString("frame", frame.getId().toString());
nbt.putString("wheels", wheels.getId().toString());
nbt.putString("engine", engine.getId().toString());
nbt.put("rearAttachment", rearAttachment.toNbt());
nbt.put("frontAttachment", frontAttachment.toNbt());
nbt.putFloat("engineSpeed", engineSpeed);
nbt.putFloat("boostSpeed", boostSpeed);
nbt.putInt("boostTimer", boostTimer);
nbt.putFloat("boostPower", boostPower);
nbt.putFloat("speedDirection", speedDirection);
nbt.putFloat("verticalSpeed", vSpeed);
nbt.putFloat("horizontalSpeed", hSpeed);
nbt.put("addedVelocity", AUtils.v3dToNbt(addedVelocity));
nbt.put("lastVelocity", AUtils.v3dToNbt(lastVelocity));
nbt.putFloat("angularSpeed", angularSpeed);
nbt.putFloat("steering", steering);
nbt.putFloat("wheelAngle", wheelAngle);
nbt.putBoolean("drifting", drifting);
nbt.putInt("driftDir", driftDir);
nbt.putBoolean("burningOut", burningOut);
nbt.putFloat("turboCharge", turboCharge);
nbt.putFloat("acceleration", acceleration);
nbt.putFloat("brakeForce", brakeForce);
nbt.putFloat("steerLeftImpulse", steerLeftImpulse);
nbt.putBoolean("holdingDrift", holdingDrift);
nbt.putInt("fallTicks", fallTicks);
nbt.putInt("despawnTime", despawnTime);
nbt.putInt("despawnCountdown", despawnCountdown);
nbt.putBoolean("decorative", decorative);
}
private float acceleration = 0f;
private float brakeForce = 0f;
private float steerLeftImpulse = 0f;
private boolean holdingDrift = false;
private boolean prevHoldDrift = holdingDrift;
public byte compactInputData() {
int r = ((((((((isAccelerating() ? 1 : 0) << 1) | (isBraking() ? 1 : 0)) << 1) | (isSteeringLeft() ? 1 : 0)) << 1) | (isSteeringRight() ? 1 : 0)) << 1) | (holdingDrift ? 1 : 0);
return (byte) r;
}
public void readCompactedInputData(byte data) {
// TODO: I'm unsure if the server needs to know the exact input state
int d = data;
holdingDrift = (1 & d) > 0;
d = d >> 0b1;
boolean steeringRight = (1 & d) > 0;
d = d >> 0b1;
boolean steeringLeft = (1 & d) > 0;
d = d >> 0b1;
brakeForce = (1 & d) > 0 ? 1f : 0f;
d = d >> 0b1;
acceleration = (1 & d) > 0 ? 1f : 0f;
steerLeftImpulse = steeringLeft ? 1f : steeringRight ? -1f : 0f;
if (steeringLeft && steeringRight) steerLeftImpulse = 0f;
}
public boolean isAccelerating() {
return acceleration > 0f;
}
public boolean isBraking() {
return brakeForce > 0f;
}
public boolean isSteeringLeft() {
return steerLeftImpulse > 0f;
}
public boolean isSteeringRight() {
return steerLeftImpulse < 0f;
}
public AutomobileEntity(EntityType<?> type, Level world) {
super(type, world);
this.setRearAttachment(RearAttachmentType.REGISTRY.getOrDefault(null));
this.setFrontAttachment(FrontAttachmentType.REGISTRY.getOrDefault(null));
}
public AutomobileEntity(Level world) {
this(AutomobilityEntities.AUTOMOBILE.require(), world);
}
@Override
public void recreateFromPacket(ClientboundAddEntityPacket packet) {
super.recreateFromPacket(packet);
if (level().isClientSide()) {
ClientPackets.requestSyncAutomobileComponentsPacket(this);
}
}
private void controllerAction(Consumer<AutomobileController> action) {
if (this.level().isClientSide()) {
if (this.getControllingPassenger() == Minecraft.getInstance().player) {
action.accept(Platform.get().controller());
}
}
}
@Override
public AutomobileFrame getFrame() {
return frame;
}
@Override
public AutomobileWheel getWheels() {
return wheels;
}
@Override
public AutomobileEngine getEngine() {
return engine;
}
@Override
public @Nullable RearAttachment getRearAttachment() {
return rearAttachment;
}
@Override
public @Nullable FrontAttachment getFrontAttachment() {
return frontAttachment;
}
@Override
public float getSteering(float tickDelta) {
return Mth.lerp(tickDelta, lastSteering, steering);
}
@Override
public float getWheelAngle(float tickDelta) {
return Mth.lerp(tickDelta, lastWheelAngle, wheelAngle);
}
public float getBoostSpeed(float tickDelta) {
return Mth.lerp(tickDelta, lastBoostSpeed, boostSpeed);
}
@Override
public float getSuspensionBounce(float tickDelta) {
return Mth.lerp(tickDelta, lastSusBounceTimer, suspensionBounceTimer);
}
@Override
public boolean engineRunning() {
return this.boostTimer > 0 || isVehicle();
}
@Override
public float getTurboCharge() {
return turboCharge;
}
@Override
public long getTime() {
return this.clientTime;
}
public float getHSpeed() {
return hSpeed;
}
public float getVSpeed() {
return vSpeed;
}
@Override
public int getBoostTimer() {
return boostTimer;
}
public double getEffectiveSpeed() {
if (this.getControllingPassenger() instanceof Player player && player.isLocalPlayer()) {
return Math.max(this.addedVelocity.length(), Math.abs(this.hSpeed));
}
return Math.max(this.addedVelocity.length(), Math.abs(this.engineSpeed + this.boostSpeed));
}
@Override
public boolean automobileOnGround() {
return automobileOnGround;
}
@Override
public boolean debris() {
return offRoad && hSpeed != 0;
}
@Override
public Vector3f debrisColor() {
return debrisColor;
}
public boolean burningOut() {
return burningOut;
}
private void setDrifting(boolean drifting) {
if (this.level().isClientSide()) {
if (!this.drifting && drifting) {
skidSound.accept(this);
}
}
this.drifting = drifting;
}
private void setBurningOut(boolean burningOut) {
if (this.level().isClientSide() && !this.drifting && !this.burningOut && burningOut) {
skidSound.accept(this);
}
if (this.burningOut != burningOut || (this.turboCharge >= LARGE_TURBO_TIME) != burningOut) {
controllerAction(c -> c.updateMaxChargeRumbleState(burningOut));
}
this.burningOut = burningOut;
}
public boolean isDrifting() {
return this.drifting;
}
public <T extends RearAttachment> void setRearAttachment(RearAttachmentType<T> rearAttachment) {
if (rearAttachment == null) {
return;
}
if (this.rearAttachment == null || this.rearAttachment.type != rearAttachment) {
if (this.rearAttachment != null) {
this.rearAttachment.onRemoved();
}
this.rearAttachment = rearAttachment.constructor().apply(rearAttachment, this);
this.rearAttachment.setYaw(this.getYRot());
if (!level().isClientSide() && !this.rearAttachment.isRideable() && this.getPassengers().size() > 1) {
this.getPassengers().get(1).stopRiding();
}
syncAttachments();
}
}
public <T extends FrontAttachment> void setFrontAttachment(FrontAttachmentType<T> frontAttachment) {
if (frontAttachment == null) {
return;
}
if (this.frontAttachment == null || this.frontAttachment.type != frontAttachment) {
if (this.frontAttachment != null) {
this.frontAttachment.onRemoved();
}
this.frontAttachment = frontAttachment.constructor().apply(frontAttachment, this);
syncAttachments();
}
}
public void setComponents(AutomobileFrame frame, AutomobileWheel wheel, AutomobileEngine engine) {
this.frame = frame;
this.wheels = wheel;
this.engine = engine;
this.setMaxUpStep(wheels.size());
this.stats.from(frame, wheel, engine);
this.displacement.applyWheelbase(frame.model().wheelBase());
if (!level().isClientSide()) syncComponents();
}
public void forNearbyPlayers(int radius, boolean ignoreDriver, Consumer<ServerPlayer> action) {
for (Player p : level().players()) {
if (ignoreDriver && p == getFirstPassenger()) {
continue;
}
if (p.position().distanceTo(position()) < radius && p instanceof ServerPlayer player) {
action.accept(player);
}
}
}
public Vec3 getTailPos() {
return this.position()
.add(new Vec3(0, 0, this.getFrame().model().rearAttachmentPos() * 0.0625)
.yRot((float) Math.toRadians(180 - this.getYRot()))
);
}
public Vec3 getHeadPos() {
return this.position()
.add(new Vec3(0, 0, this.getFrame().model().frontAttachmentPos() * 0.0625)
.yRot((float) Math.toRadians(-this.getYRot()))
);
}
public boolean hasSpaceForPassengers() {
return (this.rearAttachment.isRideable()) ? (this.getPassengers().size() < 2) : (!this.isVehicle());
}
public void setSpeed(float horizontal, float vertical) {
this.hSpeed = horizontal;
this.vSpeed = vertical;
}
@Override
public void tick() {
boolean first = this.firstTick;
if (lastWheelAngle != wheelAngle) markDirty();
lastWheelAngle = wheelAngle;
if (!this.wasEngineRunning && this.engineRunning() && this.level().isClientSide()) {
engineSound.accept(this);
}
this.wasEngineRunning = this.engineRunning();
if (!this.isVehicle() || !this.getFrontAttachment().canDrive(this.getFirstPassenger())) {
setInputs(0f, 0f, 0f, false);
}
if (this.jumpCooldown > 0) {
this.jumpCooldown--;
}
super.tick();
if (!this.rearAttachment.type.isEmpty()) this.rearAttachment.tick();
if (!this.frontAttachment.type.isEmpty()) this.frontAttachment.tick();
var prevPos = this.position();
positionTrackingTick();
collisionStateTick();
steeringTick();
driftingTick();
burnoutTick();
movementTick();
if (this.isControlledByLocalInstance()) {
this.move(MoverType.SELF, this.getDeltaMovement());
}
postMovementTick();
if (!level().isClientSide()) {
var prevTailPos = this.prevTailPos != null ? this.prevTailPos : this.getTailPos();
var tailPos = this.getTailPos();
this.rearAttachment.pull(prevTailPos.subtract(tailPos));
this.prevTailPos = tailPos;
if (dirty) {
syncData();
dirty = false;
}
if (this.hasSpaceForPassengers() && !decorative) {
var touchingEntities = this.level().getEntities(this, this.getBoundingBox().inflate(0.2, 0, 0.2), EntitySelector.pushableBy(this));
for (Entity entity : touchingEntities) {
if (!entity.hasPassenger(this)) {
if (!entity.isPassenger() && entity.getBbWidth() <= this.getBbWidth() && entity instanceof Mob && !(entity instanceof WaterAnimal)) {
entity.startRiding(this);
}
}
}
}
if (this.isVehicle()) {
if (this.getFrontAttachment().canDrive(this.getFirstPassenger()) && this.getFirstPassenger() instanceof Mob mob) {
provideMobDriverInputs(mob);
}
this.despawnCountdown = 0;
} else if (this.despawnTime > 0) {
this.despawnCountdown++;
if (this.despawnCountdown >= this.despawnTime) {
this.destroyAutomobile(false, RemovalReason.DISCARDED);
}
}
} else {
clientTime++;
lastSusBounceTimer = suspensionBounceTimer;
if (suspensionBounceTimer > 0) {
suspensionBounceTimer--;
}
if (Math.abs(this.hSpeed) < 0.05 && !this.burningOut && this.getControllingPassenger() instanceof Player) {
this.standStillTime = AUtils.shift(this.standStillTime, 0.05f, 1f);
} else {
this.standStillTime = AUtils.shift(this.standStillTime, 0.15f, -1.3f);
}
}
displacementTick(first || (this.position().subtract(prevPos).length() > 0 || this.getYRot() != this.yRotO));
}
public void positionTrackingTick() {
if (this.isControlledByLocalInstance()) {
this.lerpTicks = 0;
syncPacketPositionCodec(getX(), getY(), getZ());
} else if (lerpTicks > 0) {
this.setPos(
this.getX() + ((this.trackedX - this.getX()) / (double)this.lerpTicks),
this.getY() + ((this.trackedY - this.getY()) / (double)this.lerpTicks),
this.getZ() + ((this.trackedZ - this.getZ()) / (double)this.lerpTicks)
);
this.setYRot(this.getYRot() + (Mth.wrapDegrees(this.trackedYaw - this.getYRot()) / (float)this.lerpTicks));
this.lerpTicks--;
}
}
public void markDirty() {
dirty = true;
}
private void syncData() {
forNearbyPlayers(200, true, player -> CommonPackets.sendSyncAutomobileDataPacket(this, player));
}
private void syncComponents() {
forNearbyPlayers(200, false, player -> CommonPackets.sendSyncAutomobileComponentsPacket(this, player));
}
private void syncAttachments() {
forNearbyPlayers(200, false, player -> CommonPackets.sendSyncAutomobileAttachmentsPacket(this, player));
}
public ItemStack asPrefabItem() {
var stack = new ItemStack(AutomobilityItems.AUTOMOBILE.require());
var automobile = stack.getOrCreateTagElement("Automobile");
automobile.putString("frame", frame.getId().toString());
automobile.putString("wheels", wheels.getId().toString());
automobile.putString("engine", engine.getId().toString());
return stack;
}
@Nullable
@Override
public ItemStack getPickResult() {
return asPrefabItem();
}
// making mobs drive automobiles
// technically the mobs don't drive, instead the automobile
// self-drives to the mob's destination...
public void provideMobDriverInputs(Mob driver) {
// Don't move if the driver doesn't exist or can't drive
if (driver == null || driver.isDeadOrDying() || driver.isRemoved()) {
if (isAccelerating() || isSteeringLeft() || isSteeringRight()) markDirty();
setInputs(0f, 0f, 0f, holdingDrift);
return;
}
var path = driver.getNavigation().getPath();
// checks if there is a current, incomplete path that the entity has targeted
if (path != null && !path.isDone() && path.getEndNode() != null) {
// determines the relative position to drive to, based on the end of the path
var pos = path.getEndNode().asVec3().subtract(position());
// determines the angle to that position
double target = Mth.wrapDegrees(Math.toDegrees(Math.atan2(pos.x(), pos.z())));
// determines another relative position, this time to the path's current node (in the case of the path directly to the end being obstructed)
var fnPos = path.getNextNode().asVec3().subtract(position());
// determines the angle to that current node's position
double fnTarget = Mth.wrapDegrees(Math.toDegrees(Math.atan2(fnPos.x(), fnPos.z())));
// if the difference in angle between the end position and the current node's position is too great,
// the automobile will drive to that current node under the assumption that the path directly to the
// end is obstructed
if (Math.abs(target - fnTarget) > 69) {
pos = fnPos;
target = fnTarget;
}
// fixes up the automobile's own yaw value
float yaw = Mth.wrapDegrees(-getYRot());
// finds the difference between the target angle and the yaw
double offset = Mth.wrapDegrees(yaw - target);
// whether the automobile should go in reverse
boolean reverse = false;
// a value to determine the threshold used to determine whether the automobile is moving
// both slow enough and is at an extreme enough offset angle to incrementally move in reverse
float mul = 0.5f + (Mth.clamp(hSpeed, 0, 1) * 0.5f);
if (pos.length() < 20 * mul && Math.abs(offset) > 180 - (170 * mul)) {
long time = level().getGameTime();
// this is so that the automobile alternates between reverse and forward,
// like a driver would do in order to angle their vehicle toward a target location
reverse = (time % 80 <= 30);
}
// set the accel/brake inputs
acceleration = !reverse ? 1f : 0f;
brakeForce = reverse ? 1f : 0f;
// set the steering inputs, with a bit of a dead zone to prevent jittering
if (offset < -7) {
steerLeftImpulse = reverse ? -1f : 1f;
} else if (offset > 7) {
steerLeftImpulse = reverse ? 1f : -1f;
}
markDirty();
} else {
if (isAccelerating() || isSteeringLeft() || isSteeringRight()) markDirty();
acceleration = 0f;
steerLeftImpulse = 0f;
}
}
public void movementTick() {
// Handles boosting
lastBoostSpeed = boostSpeed;
if (boostTimer > 0) {
boostTimer--;
boostSpeed = Math.min(boostPower, boostSpeed + 0.09f);
if (engineSpeed < stats.getComfortableSpeed()) {
engineSpeed += 0.012f;
}
markDirty();
if (boostTimer == 0) {
controllerAction(c -> c.updateBoostingRumbleState(false, 0));
}
} else {
boostSpeed = AUtils.zero(boostSpeed, 0.09f);
}
// Get block below's friction
var blockBelow = new BlockPos((int) getX(), (int) (getY() - 0.05), (int) getZ());
this.grip = 1 - ((Mth.clamp((level().getBlockState(blockBelow).getBlock().getFriction() - 0.6f) / 0.4f, 0, 1) * (1 - stats.getGrip() * 0.8f)));
this.grip *= this.grip;
// Bounce on gel
if (this.automobileOnGround && this.jumpCooldown <= 0 && level().getBlockState(this.blockPosition()).getBlock() instanceof LaunchGelBlock) {
this.setSpeed(Math.max(this.getHSpeed(), 0.1f), Math.max(this.getVSpeed(), 0.9f));
this.jumpCooldown = 5;
this.automobileOnGround = false;
}
// Track the last position of the automobile
this.lastPosForDisplacement = position();
// cumulative will be modified by the following code and then the automobile will be moved by it
// Currently initialized with the value of addedVelocity (which is a general velocity vector applied to the automobile, i.e. for when it bumps into a wall and is pushed back)
var cumulative = addedVelocity;
// Reduce gravity underwater
cumulative = cumulative.add(0, (vSpeed * (isUnderWater() ? 0.15f : 1)), 0);
// This is the general direction the automobile will move, which is slightly offset to the side when drifting
this.speedDirection = getYRot() - (drifting ? Math.min(turboCharge * 6, 43 + (-steering * 12)) * driftDir : -steering * 12); //MathHelper.lerp(grip, getYaw(), getYaw() - (drifting ? Math.min(turboCharge * 6, 43 + (-steering * 12)) * driftDir : -steering * 12));
// Handle acceleration
if (isAccelerating()) {
float speed = Math.max(this.engineSpeed, 0) * acceleration;
// yeah ...
this.engineSpeed +=
// The following conditions check whether the automobile should NOT receive normal acceleration
// It will not receive this acceleration if the automobile is steering or tight-drifting
(
(this.drifting && AUtils.haveSameSign(this.steering, this.driftDir)) ||
(!this.drifting && this.steering != 0 && hSpeed > 0.5)
) ? (this.hSpeed < stats.getComfortableSpeed() ? 0.001 : 0) // This will supply a small amount of acceleration if the automobile is moving slowly only
// Otherwise, it will receive acceleration as normal
// It will receive this acceleration if the automobile is moving straight or wide-drifting (the latter slightly reduces acceleration)
: calculateAcceleration(speed, stats) * (drifting ? 0.86 : 1) * (engineSpeed > stats.getComfortableSpeed() ? 0.25f : 1) * grip;
}
// Handle braking/reverse
if (isBraking()) {
this.engineSpeed = Math.max(this.engineSpeed - 0.15f, -0.25f) * brakeForce;
}
// Handle when the automobile is rolling to a stop
if (!isAccelerating() && !isBraking()) {
this.engineSpeed = AUtils.zero(this.engineSpeed, 0.025f);
}
// Slow the automobile a bit while steering and moving fast
if (!drifting && steering != 0 && hSpeed > 0.8) {
engineSpeed -= engineSpeed * 0.00042f;
}
if (this.burningOut()) {
engineSpeed *= 0.5f;
}
// Allows for the sticky slope effect to continue for a tick after not being on a slope
// This prevents the automobile from randomly jumping if it's moving down a slope quickly
var below = new BlockPos((int) getX(), (int) (getY() - 0.51), (int) getZ());
var state = level().getBlockState(below);
if (state.is(Automobility.STICKY_SLOPES)) {
slopeStickingTimer = 1;
} else {
slopeStickingTimer = Math.max(0, slopeStickingTimer--);
}
boolean wasOffRoad = this.offRoad && this.hSpeed > 0.01;
// Handle being in off-road
if (boostSpeed < 0.4f && level().getBlockState(blockPosition()).getBlock() instanceof OffRoadBlock block) {
int layers = level().getBlockState(blockPosition()).getValue(OffRoadBlock.LAYERS);
float cap = stats.getComfortableSpeed() * (1 - ((float)layers / 3.5f));
engineSpeed = Math.min(cap, engineSpeed);
this.debrisColor = block.color;
this.offRoad = true;
} else this.offRoad = false;
if ((this.offRoad && this.hSpeed > 0.01) != wasOffRoad) {
controllerAction(c -> c.updateOffRoadRumbleState(this.offRoad));
}
// Set the horizontal speed
if (!burningOut()) hSpeed = engineSpeed + boostSpeed;
// Sticking to sticky slopes
double lowestPrevYDisp = 0;
for (double d : prevYDisplacements) {
lowestPrevYDisp = Math.min(d, lowestPrevYDisp);
}
if (slopeStickingTimer > 0 && automobileOnGround && lowestPrevYDisp <= 0) {
double cumulHSpeed = Math.sqrt((cumulative.x * cumulative.x) + (cumulative.z * cumulative.z));
cumulative = cumulative.add(0, -(0.25 + cumulHSpeed), 0);
}
float angle = (float) Math.toRadians(-speedDirection);
if (this.burningOut()) {
if (Math.abs(hSpeed) > 0.02) {
this.addedVelocity = new Vec3(Math.sin(angle) * hSpeed, 0, Math.cos(angle) * hSpeed);
this.hSpeed = 0;
cumulative = cumulative.add(addedVelocity);
}
} else {
// Apply the horizontal speed to the cumulative movement
cumulative = cumulative.add(Math.sin(angle) * hSpeed, 0, Math.cos(angle) * hSpeed);
}
cumulative = cumulative.scale(this.grip).add(this.lastVelocity.scale(1 - this.grip));
if (cumulative.length() < 0.001) {
cumulative = Vec3.ZERO;
}
// Turn the wheels
float wheelCircumference = (float)(2 * (wheels.model().radius() / 16) * Math.PI);
if (hSpeed > 0) markDirty();
wheelAngle += 300 * (hSpeed / wheelCircumference) + (hSpeed > 0 ? ((1 - grip) * 15) : 0); // made it a bit slower intentionally, also make it spin more when on slippery surface
// Set the automobile's velocity
if (this.isControlledByLocalInstance()) {
this.setDeltaMovement(cumulative);
}
this.markHurt();
this.hasImpulse = true;
lastVelocity = cumulative;
// Damage and launch entities that are hit by a moving automobile
if (Math.abs(hSpeed) > 0.2) {
runOverEntities(cumulative);
}
}
public void runOverEntities(Vec3 velocity) {
var frontBox = getBoundingBox().move(velocity.scale(0.5));
var velAdd = velocity.add(0, 0.1, 0).scale(3);
for (var entity : level().getEntities(EntityTypeTest.forClass(Entity.class), frontBox, entity -> entity != this && entity != getFirstPassenger())) {
if (!entity.isInvulnerable()) {
if (entity instanceof LivingEntity living && entity.getVehicle() != this) {
AutomobilityEntities.automobileDamageSource(level()).ifPresent(dmg -> living.hurt(dmg, hSpeed * 10));
entity.push(velAdd.x, velAdd.y, velAdd.z);
}
}
}
}
public void postMovementTick() {
float addedVelReduction = 0.1f;
if (this.burningOut()) {
addedVelReduction = 0.05f;
}
// Reduce the values of addedVelocity incrementally
double addVelLen = addedVelocity.length();
if (addVelLen > 0) addedVelocity = addedVelocity.scale(Math.max(0, addVelLen - addedVelReduction) / addVelLen);
float angle = (float) Math.toRadians(-speedDirection);
if (touchingWall && hSpeed > 0.1 && addedVelocity.length() <= 0) {
engineSpeed /= 3.6;
double knockSpeed = ((-0.2 * hSpeed) - 0.5);
addedVelocity = addedVelocity.add(Math.sin(angle) * knockSpeed, 0, Math.cos(angle) * knockSpeed);
level().playLocalSound(this.getX(), this.getY(), this.getZ(), AutomobilitySounds.COLLISION.require(), SoundSource.AMBIENT, 0.76f, 0.65f + (0.06f * (this.level().random.nextFloat() - 0.5f)), true);
if (isVehicle() && level().isClientSide()) {
if (getPassengers().stream().anyMatch(p -> p instanceof LocalPlayer)) {
controllerAction(c -> c.crashRumble());
}
}
}
double yDisp = position().subtract(this.lastPosForDisplacement).y();
// Increment the falling timer
if (!automobileOnGround && yDisp < 0) {
fallTicks += 1;
} else {
fallTicks = 0;
}
// Handle launching off slopes
double highestPrevYDisp = 0;
for (double d : prevYDisplacements) {
highestPrevYDisp = Math.max(d, highestPrevYDisp);
}
if (wasOnGround && !automobileOnGround && !isFloorDirectlyBelow) {
vSpeed = (float)Mth.clamp(highestPrevYDisp, 0, hSpeed * 0.6f);
}
// Handles gravity
vSpeed = Math.max(vSpeed - 0.08f, !automobileOnGround ? TERMINAL_VELOCITY : -0.01f);
// Store previous y displacement to use when launching off slopes
prevYDisplacements.push(yDisp);
if (prevYDisplacements.size() > 2) {
prevYDisplacements.removeLast();
}
// Handle setting the locked view offset
if (hSpeed != 0) {
float vOTarget = (drifting ? driftDir * -23 : steering * -5.6f);
if (vOTarget == 0) lockedViewOffset = AUtils.zero(lockedViewOffset, 2.5f);
else {
if (lockedViewOffset < vOTarget) lockedViewOffset = Math.min(lockedViewOffset + 3.7f, vOTarget);
else lockedViewOffset = Math.max(lockedViewOffset - 3.7f, vOTarget);
}
}
float newAngularSpeed = this.angularSpeed;
if (this.burningOut()) {
float speed = (float) this.addedVelocity.length();
float acc = (1.7f / (1 + this.frame.weight())) + (4 * speed);
float lim = 9 + (4 * speed);
if (this.steering != 0) {
newAngularSpeed = Mth.clamp(newAngularSpeed + (acc * this.steering), -lim, lim);
} else {
newAngularSpeed = AUtils.shift(newAngularSpeed, acc * 0.5f, 0);
}
} else if (hSpeed != 0) {
float traction = (1 / (1 + (4 * this.hSpeed))) + (0.3f * this.stats.getGrip());