-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathentity.py
1411 lines (1092 loc) · 42.7 KB
/
entity.py
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
"""Rendering, representation, and behavior of entities is handled here.
Entity models are made up of bones. Each bone is individually posable.
Each bone is made up of cubes, which stay in a fixed arrangement.
Every entity has a `kind`, which determines its attributes and behavior.
For behavior, an `Ai` is used. This simply stores a list of `Task`s.
Tasks run every tick until they are interrupted by a task with a higher
priority, or when they mark themselves as finished.
For example, most entities have a `WanderTask` with low priority, so when
they do not have any other goals, they will occasionally move around.
"""
from typing import List, Tuple, Optional, Any
import json
from json import JSONDecoder
import numpy as np
import heapq
import math
import time
import random
import decimal
import copy
import molang
import model
import functools
import config
from abc import ABC, abstractmethod
from sound import Sound
from inventory import Stack
from util import BlockPos, roundHalfUp, ItemId
from dataclasses import dataclass
from OpenGL.GL import * #type:ignore
from nbt import nbt
CUBE_MESH_VERTICES = np.array([
# Left face
-0.5, 0.5, 0.5, 1.0, 1.0, # top-right
-0.5, 0.5, -0.5, 0.0, 1.0, # top-left
-0.5, -0.5, -0.5, 0.0, 0.0, # bottom-left
-0.5, -0.5, -0.5, 0.0, 0.0, # bottom-left
-0.5, -0.5, 0.5, 1.0, 0.0, # bottom-right
-0.5, 0.5, 0.5, 1.0, 1.0, # top-right
# Right face
0.5, 0.5, 0.5, 0.0, 1.0, # top-left
0.5, -0.5, -0.5, 1.0, 0.0, # bottom-right
0.5, 0.5, -0.5, 1.0, 1.0, # top-right
0.5, -0.5, -0.5, 1.0, 0.0, # bottom-right
0.5, 0.5, 0.5, 0.0, 1.0, # top-left
0.5, -0.5, 0.5, 0.0, 0.0, # bottom-left
# Back face
-0.5, -0.5, -0.5, 0.0, 0.0, # Bottom-left
0.5, 0.5, -0.5, 1.0, 1.0, # top-right
0.5, -0.5, -0.5, 1.0, 0.0, # bottom-right
0.5, 0.5, -0.5, 1.0, 1.0, # top-right
-0.5, -0.5, -0.5, 0.0, 0.0, # bottom-left
-0.5, 0.5, -0.5, 0.0, 1.0, # top-left
# Front face
-0.5, -0.5, 0.5, 0.0, 0.0, # bottom-left
0.5, -0.5, 0.5, 1.0, 0.0, # bottom-right
0.5, 0.5, 0.5, 1.0, 1.0, # top-right
0.5, 0.5, 0.5, 1.0, 1.0, # top-right
-0.5, 0.5, 0.5, 0.0, 1.0, # top-left
-0.5, -0.5, 0.5, 0.0, 0.0, # bottom-left
# Bottom face
-0.5, -0.5, -0.5, 1.0, 1.0, # top-right
0.5, -0.5, -0.5, 0.0, 1.0, # top-left
0.5, -0.5, 0.5, 0.0, 0.0, # bottom-left
0.5, -0.5, 0.5, 0.0, 0.0, # bottom-left
-0.5, -0.5, 0.5, 1.0, 0.0, # bottom-right
-0.5, -0.5, -0.5, 1.0, 1.0, # top-right
# Top face
-0.5, 0.5, -0.5, 0.0, 1.0, # top-left
0.5, 0.5, 0.5, 1.0, 0.0, # bottom-right
0.5, 0.5, -0.5, 1.0, 1.0, # top-right
0.5, 0.5, 0.5, 1.0, 0.0, # bottom-right
-0.5, 0.5, -0.5, 0.0, 1.0, # top-left
-0.5, 0.5, 0.5, 0.0, 0.0, # bottom-left
], dtype='float32')
@dataclass
class Cube:
origin: Tuple[float, float, float]
size: Tuple[int, int, int]
uv: Tuple[int, int]
def toModelTk(self, app) -> model.Model:
factor = np.array([[self.size[0]], [self.size[1]], [self.size[2]]])
offset = np.array([[self.origin[0]], [self.origin[1]], [self.origin[2]]])
def trans(v):
return (((v + 0.5) * factor) + offset) / 16
return app.cube.transformed(trans)
def toVerticesGl(self) -> np.ndarray:
vertices = CUBE_MESH_VERTICES.reshape((-1, 5))
factor = np.array([self.size[0], self.size[1], self.size[2], 1.0, 1.0])
offset = np.array([self.origin[0], self.origin[1], self.origin[2], 0.0, 0.0])
# https://stackoverflow.com/questions/8486294/how-to-add-an-extra-column-to-a-numpy-array/8505658
result = (vertices + np.array([0.5, 0.5, 0.5, 0.0, 0.0])) * factor + offset
for row in range(vertices.shape[0]):
face = ['left', 'right', 'front', 'back', 'bottom', 'top'][row // 6]
if face == 'left':
uOffset = 0
uSize = self.size[2]
vOffset = 0
vSize = self.size[1]
elif face == 'front':
uOffset = self.size[2]
uSize = self.size[0]
vOffset = 0
vSize = self.size[1]
elif face == 'top':
uOffset = self.size[2]
uSize = self.size[0]
vOffset = self.size[1]
vSize = self.size[2]
elif face == 'right':
uOffset = self.size[2] + self.size[0]
uSize = self.size[2]
vOffset = 0
vSize = self.size[1]
elif face == 'back':
uOffset = 2*self.size[2] + self.size[0]
uSize = self.size[0]
vOffset = 0
vSize = self.size[1]
else: # face == 'bottom'
uOffset = self.size[2] + self.size[0]
uSize = self.size[0]
vOffset = self.size[1]
vSize = self.size[2]
uFrac = result[row, 3]
vFrac = result[row, 4]
result[row, 3] = self.uv[0] + uOffset + (1.0 - uFrac) * uSize
#result[row, 4] = (32.0 - (self.uv[1] + self.size[1] + self.size[2])) + vOffset + vFrac * vSize
result[row, 4] = (self.uv[1] + self.size[1] + self.size[2]) - (vOffset + vFrac * vSize)
return result
@dataclass
class Bone:
name: str
pivot: Tuple[float, float, float]
cubes: List[Cube]
bind_pose_rotation: Tuple[float, float, float]
neverRender: bool
def toModelTk(self, app) -> model.Model:
models = [c.toModelTk(app) for c in self.cubes]
return functools.reduce(model.Model.fuse, models, model.Model([], []))
def toVerticesGl(self) -> np.ndarray:
self.innerVertices = []
for cube in self.cubes:
vertices = cube.toVerticesGl()
pv = (self.pivot[0], self.pivot[1], self.pivot[2])
withPivot = np.hstack((vertices, np.full(shape=(vertices.shape[0], 3), fill_value=pv)))
self.innerVertices.append(withPivot)
return np.vstack(self.innerVertices)
def toVao(self) -> Tuple[int, int]:
#if self.meshVaos[meshIdx] != 0:
# glDeleteVertexArrays(1, np.array([self.meshVaos[meshIdx]])) #type:ignore
# glDeleteBuffers(1, np.array([self.meshVbos[meshIdx]])) #type:ignore
#
# self.meshVaos[meshIdx] = 0
vertices = self.toVerticesGl().flatten().astype('float32')
vao: int = glGenVertexArrays(1) #type:ignore
vbo: int = glGenBuffers(1) #type:ignore
glBindVertexArray(vao)
glBindBuffer(GL_ARRAY_BUFFER, vbo)
glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * 4, ctypes.c_void_p(0))
glEnableVertexAttribArray(0)
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 8 * 4, ctypes.c_void_p(3 * 4))
glEnableVertexAttribArray(1)
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 8 * 4, ctypes.c_void_p(5 * 4))
glEnableVertexAttribArray(2)
glBindBuffer(GL_ARRAY_BUFFER, 0)
glBindVertexArray(0)
return (vao, len(vertices) // 5)
@dataclass
class BoneAnimation:
rotation: Tuple[molang.Expr, molang.Expr, molang.Expr]
@classmethod
def fromJson(cls, j):
if 'rotation' in j:
rotation = j['rotation']
else:
rotation = [0.0, 0.0, 0.0]
if isinstance(rotation, dict):
# TODO: Keyframes
rotation = [0.0, 0.0, 0.0]
'''
for i, v in rotation.items():
if isinstance(v, list):
rotation = v
break
'''
if isinstance(rotation[0], dict):
# TODO: I don't even know what these are
rotation = [0.0, 0.0, 0.0]
x = molang.parseStr(str(rotation[0]))
y = molang.parseStr(str(rotation[1]))
z = molang.parseStr(str(rotation[2]))
return cls((x, y, z))
@dataclass
class Animation:
loop: bool
bones: dict[str, BoneAnimation]
def parseAnimation(j) -> Animation:
loop = j['loop']
bones = dict()
for (name, bone) in j['bones'].items():
bones[name] = BoneAnimation.fromJson(bone)
return Animation(loop, bones)
def openAnimations(path) -> dict[str, Animation]:
j = openCommentedJson(path)
result = {}
for (name, anim) in j['animations'].items():
if name.startswith('animation.'):
result[name] = parseAnimation(anim)
return result
@dataclass
class AnimControlState:
animations: List[Tuple[str, str]]
'''A list of animation names and their scale factors'''
transitions: List[Tuple[str, str]]
'''A list of animation names and the conditions to change to them'''
@classmethod
def fromJson(cls, j):
animations = []
try:
for anim in j['animations']:
if isinstance(anim, str):
animations.append((anim, 1))
else:
for anim, mod in anim.items():
animations.append((anim, mod))
except KeyError:
pass
transitions = []
try:
for pair in j['transitions']:
for (name, cond) in pair.items():
transitions.append((name, cond))
except KeyError:
pass
return cls(animations, transitions)
@dataclass
class AnimController:
initialState: str
states: dict[str, AnimControlState]
@classmethod
def fromJson(cls, j):
initialState = j['initial_state']
states = {}
for name, state in j['states'].items():
states[name] = AnimControlState.fromJson(state)
return cls(initialState, states)
def openAnimControllers(path) -> dict[str, AnimController]:
j = openCommentedJson(path)
result = {}
for name, val in j['animation_controllers'].items():
result[name] = AnimController.fromJson(val)
return result
def openCommentedJson(path):
with open(path) as f:
s = f.read()
try:
while True:
start = s.index('//')
end = s.index('\n', start)
s = s[:start] + s[end:]
except ValueError:
return json.loads(s)
@dataclass
class EntityRenderData:
identifier: str
#materials: dict[str, str]
#'''Maps from state name -> material name'''
textures: dict[str, str]
'''Maps from state name -> texture path'''
geometry: dict[str, str]
'''Maps from state name -> geometry ID'''
# spawn_egg
scripts: dict[str, List[str]]
'''Maps from script time -> list of scripts'''
animations: dict[str, str]
'''Maps from local animation name -> global animation name'''
animationControllers: dict[str, str]
'''Maps from local animation name -> animation controller name'''
renderControllers: List[str]
'''List of render controller names'''
enableAttachables: bool
def openRenderData(path) -> EntityRenderData:
j = openCommentedJson(path)
desc = j['minecraft:client_entity']['description']
print(path)
identifier = desc['identifier'].removeprefix('minecraft:')
#materials = desc['materials']
textures = desc['textures']
geometry = desc['geometry']
try:
scripts = desc['scripts']
except KeyError:
scripts = {}
try:
animations = desc['animations']
except KeyError:
animations = {}
try:
animationControllers = {}
for pair in desc['animation_controllers']:
for name, val in pair.items():
animationControllers[name] = val
except KeyError:
animationControllers = {}
try:
renderControllers = desc['render_controllers']
except:
renderControllers = []
try:
enableAttachables = desc['enable_attachables']
except KeyError:
enableAttachables = False
return EntityRenderData(identifier, textures, geometry, scripts,
animations, animationControllers, renderControllers, enableAttachables)
@dataclass
class EntityModel:
bones: List[Bone]
vaos: List[Tuple[int, int]]
models: List[model.Model]
def __init__(self, bones, app):
self.bones = bones
self.vaos = []
self.models = []
for bone in self.bones:
if bone.cubes == [] or bone.neverRender or 'sleeping' in bone.name:
if config.USE_OPENGL_BACKEND:
self.vaos.append((0, 0))
else:
self.models.append(model.Model([], []))
else:
if config.USE_OPENGL_BACKEND:
self.vaos.append(bone.toVao())
else:
self.models.append(bone.toModelTk(app))
def parseCube(j) -> Cube:
origin = tuple(j['origin'])
size = tuple(j['size'])
if 'uv' in j:
uv = tuple(j['uv'])
else:
# I do not understand why some of them just don't include any
uv = (0, 0)
return Cube(origin, size, uv) #type:ignore
def parseBone(j) -> Bone:
name = j['name'].lower()
if 'pivot' in j:
pivot = tuple(j['pivot'])
else:
#FIXME: ???
pivot = (0.0, 0.0, 0.0)
if 'cubes' in j:
cubes = list(map(parseCube, j['cubes']))
else:
cubes = []
if 'bind_pose_rotation' in j:
bind_pose_rotation = tuple(j['bind_pose_rotation'])
else:
bind_pose_rotation = (0.0, 0.0, 0.0)
if 'neverRender' in j:
neverRender = j['neverRender']
else:
neverRender = False
return Bone(name, pivot, cubes, bind_pose_rotation, neverRender) #type:ignore
def parseModel(j, app) -> EntityModel:
if 'bones' in j:
bones = list(map(parseBone, j['bones']))
else:
bones = []
return EntityModel(bones, app)
def merge(app, model: EntityModel, base: EntityModel) -> EntityModel:
bones = model.bones
for bone in base.bones:
if bone.name not in [b.name for b in bones]:
bones.append(bone)
return EntityModel(bones, app)
def openModels(path, app) -> dict[str, EntityModel]:
with open(path) as f:
j = json.load(f)
result = {}
for (name, model) in j.items():
if name.startswith('geometry.'):
result[name] = parseModel(model, app)
return result
#print(models['fox'].bones[3].cubes[0].toVertices())
def getHurtSound(app, entity) -> Sound:
if entity.kind.name in app.hurtSounds:
name = entity.kind.name
else:
print(f"Using fallback hurt sound for entity {entity.kind.name}")
name = 'player'
return random.choice(app.hurtSounds[name])
class ItemData:
stack: Stack
age: int
pickupDelay: int
def __init__(self):
self.stack = Stack('stone', 1)
self.age = 6000
# TODO: should increase if dropped by player or fox
self.pickupDelay = 10
def tick(self, entity: 'Entity'):
self.age -= 1
if self.age == 0:
entity.health = 0
if self.pickupDelay > 0:
self.pickupDelay -= 1
def toNbt(self) -> nbt.TAG_Compound:
tag = nbt.TAG_Compound()
tag.tags.append(nbt.TAG_Short(self.age, 'Age'))
tag.tags.append(nbt.TAG_Short(self.pickupDelay, 'PickupDelay'))
item = self.stack.toNbt()
assert(item is not None)
item.name = 'Item'
tag.tags.append(item)
return tag
def fromNbt(self, tag: nbt.TAG_Compound):
self.age = tag['Age'].value
self.pickupDelay = tag['PickupDelay'].value
self.stack = Stack.fromNbt(tag['Item'])
class TntData:
fuse: int
def __init__(self):
self.fuse = 80
def tick(self, entity: 'Entity'):
self.fuse -= 1
if self.fuse <= 0:
# TODO:
raise Exception()
def toNbt(self) -> nbt.TAG_Compound:
tag = nbt.TAG_Compound()
tag.tags.append(nbt.TAG_Short(self.fuse, 'Fuse'))
return tag
def fromNbt(self, tag: nbt.TAG_Compound):
self.fuse = tag['Fuse'].value
@dataclass
class EntityKind:
name: str
model: str
maxHealth: float
walkSpeed: float
radius: float
height: float
ai: 'Ai'
extraData: Optional[Any]
def __init__(self, name, model, maxHealth, walkSpeed, radius, height, ai, extraData=None):
self.name = name
self.model = model
self.maxHealth = maxHealth
self.walkSpeed = walkSpeed
self.radius = radius
self.height = height
self.ai = ai
self.extraData = extraData
def registerEntityKinds(app):
app.entityKinds = {
'creeper': EntityKind(
name='creeper',
model='geometry.creeper',
maxHealth=20.0,
walkSpeed=0.05,
radius=0.3,
height=1.7,
ai=Ai([WanderTask()])
),
'zombie': EntityKind(
name='zombie',
model='geometry.humanoid',
maxHealth=20.0,
walkSpeed=0.05,
radius=0.3,
height=1.9,
ai=Ai([AttackTask(), FollowTask(), WanderTask()])
),
'skeleton': EntityKind(
name='skeleton',
model='geometry.skeleton',
maxHealth=20.0,
walkSpeed=0.05,
radius=0.3,
height=1.9,
ai=Ai([AttackTask(), FollowTask(), WanderTask()])
),
'fox': EntityKind(
name='fox',
model='geometry.fox',
maxHealth=20.0,
walkSpeed=0.1,
radius=0.35,
height=0.6,
ai=Ai([FollowTask(), WanderTask()])
),
'player': EntityKind(
name='player',
model='geometry.humanoid',
maxHealth=20.0,
walkSpeed=0.2,
radius=0.3,
height=1.5,
ai=Ai([NullTask()]),
),
'item': EntityKind(
name='item',
model='geometry.item',
maxHealth=5.0,
walkSpeed=0.0,
radius=0.1,
height=0.2,
ai=Ai([NullTask()]),
extraData=ItemData(),
),
'tnt': EntityKind(
name='tnt',
model='geometry.tnt',
maxHealth=20.0,
walkSpeed=0.0,
radius=0.5,
height=1.0,
ai=Ai([NullTask()]),
extraData=TntData(),
),
}
class Entity:
pos: List[float]
velocity: List[float]
kind: EntityKind
health: float
radius: float
height: float
onGround: bool
walkSpeed: float
bodyAngle: float
headYaw: float
headPitch: float
lifeTime: float
distanceMoved: float
modifMoveSpeed: float
portalCooldown: int
path: List[BlockPos]
variables: dict[str, float]
ai: 'Ai'
extra: Optional[Any]
entityId: int
def __init__(self, app, entityId: int, kind: str = '', x: float = 0.0, y: float = 0.0, z: float = 0.0, nbt: Optional[nbt.TAG_Compound] = None):
if nbt is None:
self.pos = [x, y, z]
self.lastPos = [x, y, z]
self.velocity = [0.0, 0.0, 0.0]
self.onGround = False
self.entityId = entityId
self.bodyAngle = 0.0
self.headPitch = 0.0
self.headYaw = 0.0
self.immunity = 0
self.portalCooldown = 300
self.path = []
self.kind = app.entityKinds[kind]
self.variables = {}
self.lastClientTick = time.time() - 0.05
self.lastRender = time.time()
self.lifeTime = 0
self.distanceMoved = 0.0
self.modifMoveSpeed = 0.0
self.scriptsInit = False
self.radius = self.kind.radius
self.height = self.kind.height
self.walkSpeed = self.kind.walkSpeed
self.health = self.kind.maxHealth
self.ai = copy.deepcopy(self.kind.ai)
self.extra = copy.deepcopy(self.kind.extraData)
else:
self.fromNbt(app, entityId, nbt)
def fromNbt(self, entityId: int, app, data: nbt.TAG_Compound):
kind = data["id"].value.removeprefix("minecraft:")
Entity.__init__(self, entityId, app, kind=kind)
self.pos = [tag.value for tag in data["Pos"].tags]
self.velocity = [tag.value for tag in data["Motion"].tags]
self.health = data["Health"].value
self.onGround = data["OnGround"].value
if self.extra is not None:
self.extra.fromNbt(data)
def toNbt(self) -> nbt.TAG_Compound:
data = nbt.TAG_Compound()
motion = nbt.TAG_List(name="Motion", type=nbt.TAG_Double)
motion.append(nbt.TAG_Double(self.velocity[0]))
motion.append(nbt.TAG_Double(self.velocity[1]))
motion.append(nbt.TAG_Double(self.velocity[2]))
data.tags.append(motion)
pos = nbt.TAG_List(name="Pos", type=nbt.TAG_Double)
pos.append(nbt.TAG_Double(self.pos[0]))
pos.append(nbt.TAG_Double(self.pos[1]))
pos.append(nbt.TAG_Double(self.pos[2]))
data.tags.append(pos)
data.tags.append(nbt.TAG_String(name="id", value=f"minecraft:{self.kind.name}"))
data.tags.append(nbt.TAG_Float(name="Health", value=self.health))
data.tags.append(nbt.TAG_Byte(name="OnGround", value=self.onGround))
data.tags.append(nbt.TAG_Int(name="PortalCooldown", value=self.portalCooldown))
if self.extra is not None:
extra = self.extra.toNbt()
data.tags += extra.tags
return data
def hit(self, app, damage: float, knockback: Tuple[float, float]):
if self.immunity == 0:
getHurtSound(app, self).play()
self.health -= damage
self.velocity[0] += knockback[0] * 0.25
self.velocity[1] += 0.2
self.velocity[2] += knockback[1] * 0.25
self.immunity = 10
def getAABB(self) -> Tuple[Tuple[float, float, float], Tuple[float, float, float]]:
loX = self.pos[0] - self.radius
loY = self.pos[1]
loZ = self.pos[2] - self.radius
hiX = self.pos[0] + self.radius
hiY = self.pos[1] + self.height
hiZ = self.pos[2] + self.radius
return ((loX, loY, loZ), (hiX, hiY, hiZ))
def getBlockPos(self) -> BlockPos:
bx = roundHalfUp(self.pos[0])
by = roundHalfUp(self.pos[1])
bz = roundHalfUp(self.pos[2])
return BlockPos(bx, by, bz)
def getRotations(self, data) -> List[List[float]]:
if self.kind.name == 'item':
return [[0.0, self.lifeTime / 10.0, 0.0]]
elif self.kind.name == 'tnt':
return [[0.0, 0.0, 0.0]]
renderData: EntityRenderData = data.entityRenderData[self.kind.name]
if not self.scriptsInit and 'initialize' in renderData.scripts:
for script in renderData.scripts['initialize']:
self.runScript(script)
self.scriptsInit = True
if self.kind.name == 'zombie' or self.kind.name == 'player':
self.variables['tcos0'] = molang.evalString("(Math.cos(query.modified_distance_moved * 38.17) * query.modified_move_speed / variable.gliding_speed_value) * 57.3", self)
elif self.kind.name == 'creeper':
self.variables['leg_rot'] = molang.evalString("Math.cos(query.modified_distance_moved * 38.17326) * 80.22 * query.modified_move_speed", self)
entityAnimations: dict[str, Animation] = data.entityAnimations
anims = [entityAnimations['animation.common.look_at_target']]
if self.kind.name == 'creeper':
anims.append(entityAnimations['animation.creeper.legs'])
elif self.kind.name == 'fox':
anims.append(entityAnimations['animation.quadruped.walk'])
elif self.kind.name == 'zombie':
anims.append(entityAnimations['animation.humanoid.move'])
elif self.kind.name == 'player':
anims.append(entityAnimations['animation.humanoid.move'])
anims.append(entityAnimations['animation.humanoid.bob'])
elif self.kind.name == 'skeleton':
anims.append(entityAnimations['animation.humanoid.bow_and_arrow'])
else:
raise Exception(self.kind)
model: EntityModel = data.entityModels[renderData.geometry['default']]
result = []
for bone in model.bones:
boneName = bone.name
rot = list(copy.copy(bone.bind_pose_rotation))
for anim in anims:
if boneName in anim.bones:
rotExpr = anim.bones[boneName].rotation
rot[0] += rotExpr[0].evalWith(self)
rot[1] += rotExpr[1].evalWith(self)
rot[2] += rotExpr[2].evalWith(self)
rot[0] = math.radians(rot[0])
rot[1] = math.radians(rot[1])
rot[2] = math.radians(rot[2])
result.append(rot)
return result
'''
def getAnims(self, animName, data) -> List[str]:
renderData: EntityRenderData = data.entityRenderData[self.kind.name]
if animName in renderData.animations:
realName = renderData.animations[animName]
else:
realName = renderData.animationControllers[animName]
if realName.startswith('controller'):
anim = data.entityAnimControllers[realName]
state: AnimControlState = anim.states[anim.initialState]
result = []
for a, _ in state.animations:
if 'first_person' in a: continue
result += self.getAnims(a, data)
return result
else:
# FIXME:
if 'first_person' in animName:
return []
else:
return [animName]
'''
def _getRotation(self, data, i):
if self.kind.name == 'item':
return [0.0, self.lifeTime / 10.0, 0.0]
renderData: EntityRenderData = data.entityRenderData[self.kind.name]
model: EntityModel = data.entityModels[renderData.geometry['default']]
'''
if 'pre_animation' in renderData.scripts:
for script in renderData.scripts['pre_animation']:
self.runScript(script)
'''
bone = model.bones[i]
boneName = bone.name
(rotX, rotY, rotZ) = bone.bind_pose_rotation
#anims = [data.entityAnimations[animId] for animId in renderData.animations.values() if 'controller' not in animId]
'''
if 'animate' in renderData.scripts:
for script in renderData.scripts['animate']:
if isinstance(script, str):
for animId in self.getAnims(script, data):
animId = renderData.animations[animId]
anim = data.entityAnimations[animId]
if boneName in anim.bones:
(x, y, z) = anim.bones[boneName].rotation
rotX += molang.evalExpr(x, self)
rotY += molang.evalExpr(y, self)
rotZ += molang.evalExpr(z, self)
else:
raise Exception(self.kind)
'''
'''
if self.kind.name == 'zombie':
self.variables['tcos0'] = molang.evalString("(Math.cos(query.modified_distance_moved * 38.17) * query.modified_move_speed / variable.gliding_speed_value) * 57.3", self)
elif self.kind.name == 'creeper':
self.variables['leg_rot'] = molang.evalString("Math.cos(query.modified_distance_moved * 38.17326) * 80.22 * query.modified_move_speed", self)
'''
'''
#if anim is not None:
# print(boneName)
for ctrlName in renderData.animationControllers:
for animId in self.getAnims(ctrlName, data):
animId = renderData.animations[animId]
anim = data.entityAnimations[animId]
if boneName in anim.bones:
# FIXME:
if not isinstance(anim.bones[boneName].rotation, dict):
(x, y, z) = anim.bones[boneName].rotation
rotX += molang.evalExpr(x, self)
rotY += molang.evalExpr(y, self)
rotZ += molang.evalExpr(z, self)
'''
'''
if self.kind.name == 'item':
rot = [0.0, self.lifeTime * 3.0, 0.0]
elif boneName == 'head':
rot = [math.degrees(self.headPitch), math.degrees(self.headYaw - self.bodyAngle), 0.0]
elif anim is not None and boneName in anim.bones:
(x, y, z) = anim.bones[boneName].rotation
rot = [self.calc(x), self.calc(y), self.calc(z)]
else:
rot = [0.0, 0.0, 0.0]
'''
rotX = math.radians(rotX)
rotY = math.radians(rotY)
rotZ = math.radians(rotZ)
return (rotX, rotY, rotZ)
def getQuery(self, name):
if name == 'target_x_rotation':
return math.degrees(self.headPitch)
elif name == 'target_y_rotation':
return math.degrees(self.headYaw - self.bodyAngle)
elif name == 'modified_move_speed':
return self.modifMoveSpeed
elif name == 'modified_distance_moved':
return self.distanceMoved
elif name == 'vertical_speed':
return self.velocity[1]
elif name == 'life_time':
return self.lifeTime
elif name == 'anim_time':
# TODO:
return self.lifeTime
elif name == 'swell_amount':
return 0.0
elif name == 'is_on_ground':
return 1.0 if self.onGround else 0.0
elif name == 'is_alive':
return 1.0 if self.health > 0.0 else 0.0
elif name == 'position_delta0':
# TODO:
return 0.0
elif name == 'position_delta1':
# TODO:
return 0.0
elif name == 'position_delta2':
# TODO:
return 0.0
elif name == 'main_hand_item_use_duration':
# TODO:
return 5.0