-
Notifications
You must be signed in to change notification settings - Fork 15
/
EntitiePlugin.py
2393 lines (2188 loc) · 120 KB
/
EntitiePlugin.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
#By PremiereHell ,
# Thanks To StealthyX https://github.com/StealthyExpertX/Amulet-Plugins
# For Getting me started on this, He provided some code that got me started on this.
import math
import time
import struct
from amulet_map_editor.programs.edit.api.events import (
EVT_SELECTION_CHANGE,
)
import amulet_nbt
import wx
import collections
import os
from os.path import exists
import numpy
import uuid
from amulet.api.block_entity import BlockEntity
from amulet.api.block import Block
from typing import TYPE_CHECKING, Type, Any, Callable, Tuple, BinaryIO, Optional, Union
from amulet.utils import world_utils
from amulet_map_editor.api.opengl.camera import Projection
from amulet_map_editor.programs.edit.api.behaviour import BlockSelectionBehaviour
from amulet.api.selection import SelectionGroup
from amulet.api.selection import SelectionBox
from amulet.utils import block_coords_to_chunk_coords
from amulet.level.formats.anvil_world.region import AnvilRegion
from amulet_map_editor.programs.edit.api.operations import DefaultOperationUI
from amulet_map_editor.api.wx.ui.base_select import BaseSelect
from amulet.api.errors import ChunkDoesNotExist
import amulet_nbt as Nbt
if TYPE_CHECKING:
from amulet.api.level import BaseLevel
from amulet_map_editor.programs.edit.api.canvas import EditCanvas
class BedRock(wx.Panel):
def __int__(self, world, canvas):
wx.Panel.__init__(self, parent)
self.world = world
self.canvas = canvas
def get_raw_data_new_version(self, is_export=False, all_enty=False):
self.get_all_flag = all_enty
self.EntyData = []
self.Key_tracker = []
self.lstOfE = []
select_chunks = self.canvas.selection.selection_group.chunk_locations() # selection_group.chunk_locations()
all_chunks = [x for x in self.world.level_wrapper.all_chunk_coords(self.canvas.dimension)]
dim = struct.unpack("<i", self.get_dim_value())[0]
exclude_filter = self.exclude_filter.GetValue().split(",")
include_filter = self.include_filter.GetValue().split(",")
if all_enty:
self.canvas.selection.set_selection_group(SelectionGroup([]))
if self.canvas.selection.selection_group:
search_chunks = select_chunks
else:
search_chunks = all_chunks
for xc, zc in search_chunks:
key = (xc, zc, dim)
if self.digp.get(key) != None:
for x in self.digp.get(key):
if self.actors.get(x) != None:
for raw in self.actors.get(x):
try:
nbt = self.nbt_loder(raw)
except:
nbt = Nbt.from_snbt(raw)
name = str(nbt['identifier']).replace("minecraft:", "")
if exclude_filter != [''] or include_filter != ['']:
if name not in exclude_filter:
self.lstOfE.append(name)
self.EntyData.append(nbt.to_snbt(1))
self.Key_tracker.append(x)
if name in include_filter:
self.lstOfE.append(name)
self.EntyData.append(nbt.to_snbt(1))
self.Key_tracker.append(x)
else:
self.lstOfE.append(name)
self.EntyData.append(nbt.to_snbt(1))
self.Key_tracker.append(x)
if is_export:
print("Exporting")
return self.EntyData
if len(self.EntyData) > 0:
zipped_lists = zip(self.lstOfE, self.EntyData, self.Key_tracker)
sorted_pairs = sorted(zipped_lists)
tuples = zip(*sorted_pairs)
self.lstOfE, self.EntyData, self.Key_tracker = [list(tuple) for tuple in tuples]
if len(self.lstOfE) == 0:
EntitiePlugin.Onmsgbox(self, "No Entities", "No Entities were found within the selecton")
else:
return self.EntyData, self.lstOfE
def delete_un_or_selected_entities(self, event, unseleted):
res = EntitiePlugin.important_question(self)
if res == False:
return
selection = self.canvas.selection.selection_group
try:
chunks = selection.chunk_locations()
for c in chunks:
self.world.get_chunk(c[0], c[1], self.canvas.dimension)
except amulet.api.errors.ChunkDoesNotExist:
responce = self.con_boc("Chuck Error", "Empty chunk selected, \n Continue any Ways?")
if responce:
print("Exiting")
return
else:
pass
if "[((0, 0, 0), (0, 0, 0))]" == str(selection):
responce = self.con_boc("No selection",
"All Entities will be deleted in " + str(self.canvas.dimension) + " \n Continue?")
if responce:
print("Exiting")
return
sel_res_text = ''
if unseleted:
all_chunks = [x for x in self.world.level_wrapper.all_chunk_coords(self.canvas.dimension)]
selected = self.canvas.selection.selection_group.chunk_locations()
sel_res_text = "Unselected"
else: # Combine Two functions into one
all_chunks = self.canvas.selection.selection_group.chunk_locations()
selected = []
sel_res_text = "Selected"
if self.world.level_wrapper.version >= (1, 18, 30, 4, 0):
self._load_entitie_data(event,False,True)
prefixList = []
tempPreKe = []
d = b''
pdig_to_delete = []
for ch in all_chunks:
if ch not in selected:
cx, cz = ch[0].to_bytes(4, 'little', signed=True), ch[1].to_bytes(4, 'little', signed=True)
if 'minecraft:the_end' in self.canvas.dimension:
d = int(2).to_bytes(4, 'little', signed=True)
elif 'minecraft:the_nether' in self.canvas.dimension:
d = int(1).to_bytes(4, 'little', signed=True)
key = b'digp' + cx + cz + d # build the digp key for the chunk
try:
if self.level_db.get(key):
data = self.level_db.get(key)
for CntB in range(0, len(data), 8): # the actorprefix keys are every 8 bytes , build a list
prefixList.append(b'actorprefix' + data[CntB:CntB + 8])
pdig_to_delete.append(key)
except KeyError as e:
print(e)
for pkey in prefixList:
self.level_db.delete(pkey)
for pdig_d in pdig_to_delete:
self.level_db.delete(pdig_d)
else:
for x, z in all_chunks:
if (x,z) not in selected:
raw = self.world.level_wrapper.get_raw_chunk_data(x, z, self.canvas.dimension)
raw[b'2'] = b''
self.world.level_wrapper.put_raw_chunk_data(x, z, raw, self.canvas.dimension)
self.world.save()
self._set_list_of_actors_digp
self._load_entitie_data(event, False, False)
EntitiePlugin.Onmsgbox(self, "Deleted ", f"Entities from {sel_res_text}")
def _exp_entitie_data(self, _):
dlg = ExportImportCostomDialog(None)
dlg.InitUI(1)
res = dlg.ShowModal()
if dlg.selected_chunks.GetValue():
select_chunks = self.canvas.selection.selection_group.chunk_locations()
elif dlg.all_chunks.GetValue():
select_chunks = [x for x in self.world.level_wrapper.all_chunk_coords(self.canvas.dimension)]
elif dlg.nbt_file_option.GetValue():
self._export_nbt(_)
return
else:
return
snbt_list = b''
world = self.world
dimension = self.canvas.dimension
selection = self.canvas.selection.selection_group
snbt_line_list = ""
dim = struct.unpack("<i", self.get_dim_value())[0]
if self.world.level_wrapper.version >= (1, 18, 30, 4, 0):
if self.canvas.selection.selection_group.selection_boxes == ():
responce = EntitiePlugin.con_boc(self, "Backup: ",
"No selection, This will back up all Entities within this Dim:\n"
+ self.canvas.dimension)
if responce == True:
return
else:
responce = EntitiePlugin.con_boc(self, "Backup",
",This will back up all Entities within this selection/s >" + str(
self.canvas.selection.selection_group))
if responce == True:
return
listOfent = self.get_raw_data_new_version(True)
if len(listOfent) > 0:
for data in listOfent:
format = Nbt.from_snbt(data)
snbt_line_list += format.to_snbt() + "\n"
responce = EntitiePlugin.save_entities_export(self, snbt_line_list)
if responce == True:
EntitiePlugin.Onmsgbox(self, "Export Complete", "No Erros were detected")
else:
EntitiePlugin.Onmsgbox(self, "Cancel", "Canceled or something went wrong")
return
else:
ent = {}
chunks = select_chunks
byteCount = 0
snbb = []
self.EntyData.clear()
for count, (cx, cz) in enumerate(chunks):
chunk = self.world.level_wrapper.get_raw_chunk_data(cx, cz, self.canvas.dimension)
if chunk.get(b'2'):
max = len(chunk[b'2'])
pointer = 0
while pointer < max:
EntyD, p = Nbt.load(chunk[b'2'][pointer:], little_endian=True, offset=True)
pointer += p
self.EntyData.append(EntyD)
if len(self.EntyData) > 0:
for elist in self.EntyData:
snbt_line_list += elist.to_snbt() + "\n"
res = EntitiePlugin.save_entities_export(self,snbt_line_list)
if res == False:
return
EntitiePlugin.Onmsgbox(self,"Export", "Saved")
def _export_nbt(self, _):
entities = amulet_nbt.TAG_List()
blocks = amulet_nbt.TAG_List()
palette = amulet_nbt.TAG_List()
DataVersion = amulet_nbt.TAG_Int(2975)
selection = self.canvas.selection.selection_group.to_box()
pallet_key_map = collections.defaultdict(list)
nbt_state_map = collections.defaultdict(list)
indx = 0
sx, sy, sz = 0, 0, 0
mx, my, mz = self.canvas.selection.selection_group.to_box().shape
block_pos = []
reps = EntitiePlugin.con_boc(self, "Air Blocks", 'Do you want to encude air block?')
# bl = np.zeros(shape, dtype=numpy.uint32)
for x in range(0, (mx)):
for y in range(0, (my)):
for z in range(0, (mz)):
block_pos.append((x, y, z))
entities = self.get_entities_nbt(block_pos)
prg_max = len(block_pos)
prg_pre = 0
prg_pre_th = len(block_pos) / 100
self.prog = wx.ProgressDialog("Saving blocks", str(0) + " of " + str(prg_max),
style=wx.PD_AUTO_HIDE | wx.PD_CAN_ABORT | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME)
self.prog.Show(True)
for i, (s, b) in enumerate(zip(selection, block_pos)):
if self.prog.WasCancelled():
self.prog.Hide()
self.prog.Destroy()
break
if i >= prg_pre_th:
prg_pre_th += len(block_pos) / 100
prg_pre += 1
self.prog.Update(prg_pre, "Saving blocks " + str(i) + " of " + str(prg_max))
block, blockEntity = self.world.get_version_block(s[0], s[1], s[2], self.canvas.dimension,
("java", (1, 18, 0)))
if not reps:
check_string = ""
else:
check_string = 'minecraft:air'
if str(block) != check_string:
if pallet_key_map.get((block.namespaced_name, str(block.properties))) == None:
pallet_key_map[(block.namespaced_name, str(block.properties))] = indx
indx += 1
palette_Properties = amulet_nbt.TAG_Compound(
{'Properties': amulet_nbt.from_snbt(str(block.properties)),
'Name': amulet_nbt.TAG_String(block.namespaced_name)})
palette.append(palette_Properties)
state = pallet_key_map[(block.namespaced_name, str(block.properties))]
if blockEntity == None:
blocks_pos = amulet_nbt.TAG_Compound({'pos': amulet_nbt.TAG_List(
[amulet_nbt.TAG_Int(b[0]), amulet_nbt.TAG_Int(b[1]),
amulet_nbt.TAG_Int(b[2])]), 'state': amulet_nbt.TAG_Int(state)})
blocks.append(blocks_pos)
else:
blocks_pos = amulet_nbt.TAG_Compound({'nbt': amulet_nbt.from_snbt(blockEntity.nbt.to_snbt()),
'pos': amulet_nbt.TAG_List(
[amulet_nbt.TAG_Int(b[0]),
amulet_nbt.TAG_Int(b[1]),
amulet_nbt.TAG_Int(b[2])]),
'state': amulet_nbt.TAG_Int(state)})
blocks.append(blocks_pos)
prg_pre = 99
self.prog.Update(prg_pre, "Finishing Up " + str(i) + " of " + str(prg_max))
size = amulet_nbt.TAG_List([amulet_nbt.TAG_Int(mx), amulet_nbt.TAG_Int(my), amulet_nbt.TAG_Int(mz)])
save_it = amulet_nbt.NBTFile()
save_it['size'] = size
save_it['entities'] = entities
save_it['blocks'] = blocks
save_it['palette'] = palette
save_it['DataVersion'] = DataVersion
raw_data = save_it.save_to(compressed=True, little_endian=False)
prg_pre = 100
self.prog.Update(prg_pre, "Done")
pathto = ""
fdlg = wx.FileDialog(self, "Save As .nbt", "", "", "nbt files(*.nbt)|*.*", wx.FD_SAVE)
if fdlg.ShowModal() == wx.ID_OK:
pathto = fdlg.GetPath()
else:
return False
if ".nbt" not in pathto:
pathto = pathto + ".nbt"
with open(pathto, "wb") as tfile:
tfile.write(raw_data)
tfile.close()
wx.MessageBox("Save Complete", "No Issues", wx.OK | wx.ICON_INFORMATION)
def _import_nbt(self, _):
fdlg = wx.FileDialog(self, "Load .nbt File", "", "", "nbt files(*.nbt)|*.*", wx.FD_OPEN)
the_id = fdlg.ShowModal()
if int(the_id) == 5101:
return False
if the_id == wx.ID_OK:
pathto = fdlg.GetPath()
nbt = amulet_nbt.load(pathto, compressed=True, little_endian=False, )
block_platform = "java"
block_version = (1, 18, 0)
b_pos = []
palette = []
Name = []
enbt = []
xx = self.canvas.selection.selection_group.min_x
yy = self.canvas.selection.selection_group.min_y
zz = self.canvas.selection.selection_group.min_z
if True:
reps = EntitiePlugin.con_boc(self, "Air Blocks", 'Do you want to encude air block?')
for x in nbt.get('blocks'):
if nbt['palette'][int(x.get('state'))].get('Properties') != None:
palette.append(
dict(amulet_nbt.from_snbt(nbt['palette'][int(x.get('state'))]['Properties'].to_snbt())))
else:
palette.append(None)
b_pos.append(x.get('pos'))
Name.append(nbt['palette'][int(x.get('state'))]['Name'])
if x.get('nbt') != None:
name = str(nbt['palette'][int(x.get('state'))]['Name']).split(':')
blockEntity = BlockEntity(name[0], name[1].replace('_', '').capitalize(), 0, 0, 0,
amulet_nbt.NBTFile(x.get('nbt')))
enbt.append(blockEntity)
else:
enbt.append(None)
if not reps:
check_string = ""
else:
check_string = 'minecraft:air'
for x in zip(b_pos, palette, Name, enbt):
if x[1] != check_string:
block = Block(str(x[2]).split(':')[0], str(x[2]).split(':')[1], x[1])
self.world.set_version_block(xx + x[0][0], yy + x[0][1], zz + x[0][2], self.canvas.dimension,
(block_platform, block_version), block, x[3])
self.canvas.run_operation(lambda: self._refresh_chunk_now(self.canvas.dimension, self.world, xx, zz))
dialog = wx.MessageDialog(self, "Including entities directly edits the world and there is no Undo."
"\n Would you like to save changes or discard them,"
"\n Both option will remove all current undo points\n"
"What do you wish to do?", "NOTICE",
wx.ICON_EXCLAMATION | wx.YES_NO | wx.CANCEL | wx.CANCEL_DEFAULT)
dialog.SetYesNoLabels('Save changes', 'Discard changes')
responce = dialog.ShowModal()
dialog.Destroy()
if responce == wx.ID_YES:
self.world.save()
self.world.purge()
pass
elif responce == wx.ID_NO:
self.world.purge()
pass
else:
return
e_nbt_list = []
for x in nbt.get('entities'):
if str(x) != '':
e_nbt = x.get('nbt')
nxx, nyy, nzz = x.get('pos').value
if 'Float' in str(type(nxx)):
x['nbt']['Pos'] = amulet_nbt.TAG_List([amulet_nbt.TAG_Float(float(nxx + xx)),
amulet_nbt.TAG_Float(float(nyy + yy)),
amulet_nbt.TAG_Float(float(nzz + zz))])
if 'Double' in str(type(nxx)):
x['nbt']['Pos'] = amulet_nbt.TAG_List([amulet_nbt.TAG_Double(float(nxx + xx)),
amulet_nbt.TAG_Double(float(nyy + yy)),
amulet_nbt.TAG_Double(float(nzz + zz))])
e_nbt_list.append(x['nbt'])
self.set_entities_nbt(e_nbt_list)
def _refresh_chunk_now(self, dimension, world, x, z):
cx, cz = block_coords_to_chunk_coords(x, z)
chunk = world.get_chunk(cx, cz, dimension)
chunk.changed = True
def get_dim_value_bytes(self):
if 'minecraft:the_end' in self.canvas.dimension:
dim = int(2).to_bytes(4, 'little', signed=True)
elif 'minecraft:the_nether' in self.canvas.dimension:
dim = int(1).to_bytes(4, 'little', signed=True)
elif 'minecraft:overworld' in self.canvas.dimension:
dim = b'' # int(0).to_bytes(4, 'little', signed=True)
return dim
def get_entities_nbt(self, rpos):
mapdic = collections.defaultdict()
entities = amulet_nbt.TAG_List()
selection = self.canvas.selection.selection_group.to_box()
for o, n in zip(selection, rpos):
mapdic[o] = n
chunk_min, chunk_max = self.canvas.selection.selection_group.min, \
self.canvas.selection.selection_group.max
min_chunk_cords, max_chunk_cords = block_coords_to_chunk_coords(chunk_min[0], chunk_min[2]), \
block_coords_to_chunk_coords(chunk_max[0], chunk_max[2])
if self.world.level_wrapper.platform == "bedrock":
if self.world.level_wrapper.version >= (1, 18, 30, 4, 0):
actorprefixs = iter(self.level_db.iterate(start=b'actorprefix',
end=b'actorprefix\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF'))
t_start = struct.pack('<ii', min_chunk_cords[0], min_chunk_cords[1])
t_end = struct.pack('<ii', max_chunk_cords[0], max_chunk_cords[1])
start = b''.join([b'digp', t_start, self.get_dim_value_bytes()])
end = b''.join([b'digp', t_end, self.get_dim_value_bytes()])
for digps_key, digps_val in self.level_db.iterate(start=start, end=end):
for x in range(0, len(digps_val), 8):
key = b''.join([b'actorprefix', digps_val[x:x + 8]])
actor = self.level_db.get(key)
nbt_data = amulet_nbt.load(actor, compressed=False, little_endian=True)
pos = nbt_data.get("Pos")
x, y, z = math.floor(pos[0]), math.floor(pos[1]), math.floor(pos[2])
if (x, y, z) in selection:
nbt_entitie = amulet_nbt.TAG_List()
new_pos = mapdic[(x, y, z)]
nbt_pos = amulet_nbt.TAG_List(
[amulet_nbt.TAG_Float(sum([new_pos[0],
math.modf(abs(nbt_data.get("Pos")[0].value))[0]])),
amulet_nbt.TAG_Float(sum([new_pos[1],
math.modf(abs(nbt_data.get("Pos")[1].value))[0]])),
amulet_nbt.TAG_Float(sum([new_pos[2],
math.modf(abs(nbt_data.get("Pos")[2].value))[0]]))])
nbt_block_pos = amulet_nbt.TAG_List([amulet_nbt.TAG_Int(new_pos[0]),
amulet_nbt.TAG_Int(new_pos[1]),
amulet_nbt.TAG_Int(new_pos[2])])
nbt_data.pop('internalComponents')
nbt_data.pop('UniqueID')
nbt_nbt = amulet_nbt.from_snbt(nbt_data.to_snbt())
main_entry = amulet_nbt.TAG_Compound()
main_entry['nbt'] = nbt_nbt
main_entry['blockPos'] = nbt_block_pos
main_entry['pos'] = nbt_pos
entities.append(main_entry)
return entities
elif self.world.level_wrapper.version < (1, 18, 30, 4, 0):
entitie = amulet_nbt.TAG_List()
for cx, cz in self.canvas.selection.selection_group.chunk_locations():
chunk = self.world.level_wrapper.get_raw_chunk_data(cx, cz, self.canvas.dimension)
if chunk.get(b'2') != None:
max = len(chunk[b'2'])
cp = 0
while cp < max:
nbt_data, p = amulet_nbt.load(chunk[b'2'][cp:], little_endian=True, offset=True)
cp += p
pos = nbt_data.get("Pos")
print(nbt_data.get('identifier'), selection.blocks)
x, y, z = math.floor(pos[0]), math.floor(pos[1]), math.floor(pos[2])
print((x, y, z) in selection)
if (x, y, z) in selection:
new_pos = mapdic[(x, y, z)]
nbt_pos = amulet_nbt.TAG_List(
[amulet_nbt.TAG_Float(sum([new_pos[0],
math.modf(abs(nbt_data.get("Pos")[0].value))[0]])),
amulet_nbt.TAG_Float(sum([new_pos[1],
math.modf(abs(nbt_data.get("Pos")[1].value))[0]])),
amulet_nbt.TAG_Float(sum([new_pos[2],
math.modf(abs(nbt_data.get("Pos")[2].value))[0]]))])
nbt_block_pos = amulet_nbt.TAG_List([amulet_nbt.TAG_Int(new_pos[0]),
amulet_nbt.TAG_Int(new_pos[1]),
amulet_nbt.TAG_Int(new_pos[2])])
nbt_data.pop('internalComponents')
nbt_data.pop('UniqueID')
nbt_nbt = amulet_nbt.from_snbt(nbt_data.to_snbt())
main_entry = amulet_nbt.TAG_Compound()
main_entry['nbt'] = nbt_nbt
main_entry['blockPos'] = nbt_block_pos
main_entry['pos'] = nbt_pos
entities.append(main_entry)
return entities
else:
print("no data")
def set_entities_nbt(self, entities_list):
entcnt = 0
if self.world.level_wrapper.platform == "bedrock":
if self.world.level_wrapper.version >= (1, 18, 30, 4, 0):
for x in entities_list:
xc, zc = block_coords_to_chunk_coords(x.get('Pos')[0], x.get('Pos')[2])
print(xc, zc)
world_count = int(str(self.world.level_wrapper.root_tag.get('worldStartCount')).replace('L', ''))
start_count = 4294967295 - world_count
entcnt += 1
actorKey = struct.pack('>LL', start_count, entcnt)
put_key = b''.join([b'actorprefix', actorKey])
digp = b''.join([b'digp', struct.pack('<ii', xc, zc), self.get_dim_value_bytes()])
try:
print(self.level_db.get(digp))
new_digp = self.level_db.get(digp)
print(self.level_db.get(digp))
except:
new_digp = b''
try:
new_actor = self.level_db.get(put_key)
except:
new_actor = b''
new_digp += actorKey
new_actor += amulet_nbt.NBTFile(x).save_to(compressed=False, little_endian=True)
self.level_db.put(put_key, new_actor)
self.level_db.put(digp, new_digp)
elif self.world.level_wrapper.version < (1, 18, 30, 4, 0):
for x in entities_list:
xc, zc = block_coords_to_chunk_coords(x.get('Pos')[0], x.get('Pos')[2])
chunk = self.world.level_wrapper.get_raw_chunk_data(xc, zc, self.canvas.dimension)
try:
chunk[b'2'] += amulet_nbt.NBTFile(x).save_to(little_endian=True, compressed=False)
except:
chunk[b'2'] = amulet_nbt.NBTFile(x).save_to(little_endian=True, compressed=False)
self.world.level_wrapper.put_raw_chunk_data(xc, zc, chunk, self.canvas.dimension)
self.world.level_wrapper.save()
self.world.save()
def _imp_entitie_data(self, _):
dlg = ExportImportCostomDialog(None)
dlg.InitUI(2)
res = dlg.ShowModal()
# self._set_list_of_actors_digp
if dlg.ms_file.GetValue():
fdlg = wx.FileDialog(self, "export Entities", "", "",
f"SNBT (*.snbt_{self.world.level_wrapper.platform})|*.*", wx.FD_OPEN)
if fdlg.ShowModal() == wx.ID_OK:
pathto = fdlg.GetPath()
else:
return
anbt = amulet_nbt.load(pathto, compressed=False, little_endian=True)
sx, sy, sz = anbt.get("structure_world_origin")
egx, egy, egz = anbt.get("size")
ex, ey, ez = sx + egx, sy + egy, sz + egz
group = []
self.canvas.camera.set_location((sx, 70, sz))
self.canvas.camera._notify_moved()
s, e = (int(sx), int(sy), int(sz)), (int(ex), int(ey), int(ez))
group.append(SelectionBox(s, e))
sel_grp = SelectionGroup(group)
self.canvas.selection.set_selection_group(sel_grp)
for xx in self.canvas.selection.selection_group.blocks:
for nbtlist in self.actors.values():
for nbt in nbtlist:
nbtd = amulet_nbt.load(nbt, compressed=False, little_endian=True)
x,y,z = nbtd.get('Pos').value
ex,ey,ez = math.floor(x),math.floor(y),math.floor(z)
if (ex,ey,ez) == xx:
print(ex,ey,ez, nbtd.value)
anbt['structure']['entities'].append(nbtd.value)
#nbt_file = amulet_nbt.NBTFile(anbt)
anbt.save_to(pathto, compressed=False, little_endian=True)
EntitiePlugin.Onmsgbox(self, "Entities Added To Structure File", "Complete")
return
elif dlg.nbt_file.GetValue():
try:
re = self._import_nbt(_)
if re == False:
return
except ValueError as e:
EntitiePlugin.Onmsgbox(self, "No Selection", "You Need to make a selection to set starting point. ")
return
EntitiePlugin.Onmsgbox(self, "NBT Import", "Complete")
elif dlg.list.GetValue():
res = EntitiePlugin.important_question(self)
if res == False:
return
snbt_loaded_list = EntitiePlugin.load_entities_export(self)
chunk_dict = collections.defaultdict(list)
NewRawB = b''
if self.world.level_wrapper.version >= (1, 18, 30, 4, 0):
ent_cnt = 2
print("Importing...")
self._set_list_of_actors_digp
for snbt_line in snbt_loaded_list:
nbt_from_snbt = Nbt.from_snbt(snbt_line)
cx, cz = block_coords_to_chunk_coords(nbt_from_snbt.get('Pos')[0], nbt_from_snbt.get('Pos')[2])
chunk_dict[(cx, cz)].append(nbt_from_snbt)
d = 0
for lk_data in chunk_dict.keys():
print(lk_data)
key = self.build_digp_chunk_key(lk_data[0], lk_data[1]) # build the digp key for the chunk
dig_p_dic = {}
dig_byte_list = b''
for ent_data in chunk_dict[lk_data]:
new_prefix = self.build_actor_key(1, ent_cnt)
ent_cnt += 1
ent_data["UniqueID"] = self._genorate_uid(ent_cnt)
try:
ent_data['internalComponents']['EntityStorageKeyComponent']['StorageKey'] = \
amulet_nbt.TAG_String(new_prefix[len(b'actorprefix'):])
except:
pass
dig_byte_list += new_prefix[len(b'actorprefix'):]
final_data = amulet_nbt.NBTFile(ent_data).save_to(compressed=False, little_endian=True)
print(new_prefix, final_data)
self.level_db.put(new_prefix, final_data)
self.level_db.put(key, dig_byte_list)
else:
cnt = 0
for snbt in snbt_loaded_list:
nbt_from_snbt = Nbt.from_snbt(snbt)
cx, cz = block_coords_to_chunk_coords(nbt_from_snbt.get('Pos')[0], nbt_from_snbt.get('Pos')[2])
chunk_dict[(cx, cz)].append(nbt_from_snbt)
for k in chunk_dict.keys():
chunk = b''
chunk = self.world.level_wrapper.get_raw_chunk_data(k[0], k[1], self.canvas.dimension)
NewRawB = []
for ent in chunk_dict[k]:
cnt += 1
ent["UniqueID"] = self._genorate_uid(cnt)
NewRawB.append(Nbt.NBTFile(ent).save_to(compressed=False, little_endian=True))
if chunk.get(b'2'):
chunk[b'2'] += b''.join(NewRawB)
else:
chunk[b'2'] = b''.join(NewRawB)
self.world.level_wrapper.put_raw_chunk_data(k[0], k[1], chunk, self.canvas.dimension)
old_start = self.world.level_wrapper.root_tag.get('worldStartCount')
self.world.level_wrapper.root_tag['worldStartCount'] = Nbt.TAG_Long((int(old_start) - 1))
self.world.level_wrapper.root_tag.save()
self.world.save()
self._set_list_of_actors_digp
self._load_entitie_data(_, False,False)
EntitiePlugin.Onmsgbox(self,"Entitie Import", "Complete")
def _genorate_uid(self, cnt):
start_c = self.world.level_wrapper.root_tag.get('worldStartCount')
new_gen = struct.pack('<LL', int(cnt), int(start_c))
new_tag = Nbt.TAG_Long(struct.unpack('<q', new_gen)[0])
return new_tag
def _storage_key_(self, val):
if isinstance(val, bytes):
return struct.unpack('>II', val)
if isinstance(val, Nbt.TAG_String):
return Nbt.TAG_Byte_Array([x for x in val.py_data])
if isinstance(val, Nbt.TAG_Byte_Array):
data = b''
for b in val: data += b
return data
def _move_copy_entitie_data(self, event, copy=False):
res = EntitiePlugin.important_question(self)
if res == False:
return
try:
data = Nbt.from_snbt(self.EntyData[self.ui_entitie_choice_list.GetSelection()])
except:
data = self.EntyData[self.ui_entitie_choice_list.GetSelection()]
if data == '':
EntitiePlugin.Onmsgbox(self,"No Data", "Did you make a selection?")
return
x = self._X.GetValue().replace(" X", "")
y = self._Y.GetValue().replace(" Y", "")
z = self._Z.GetValue().replace(" Z", "")
dim = struct.unpack("<i", self.get_dim_value())[0]
location = Nbt.TAG_List([Nbt.TAG_Float(float(x)), Nbt.TAG_Float(float(y)), Nbt.TAG_Float(float(z))])
if data != '':
if copy:
cx, cz = block_coords_to_chunk_coords(data.get('Pos')[0], data.get('Pos')[2])
actor_key = self.uuid_to_storage_key(data)
acnt = []
for x in self.actors.keys():
if x[0] == actor_key[0]:
acnt.append(x[1])
acnt.sort()
max_count_uuid = acnt[-1:][0]
wc = 4294967296 - actor_key[0]
new_actor_key = (actor_key[0],max_count_uuid+1)
new_actor_key_raw = struct.pack('>LL', new_actor_key[0], new_actor_key[1] )
new_uuid = struct.pack('<LL', max_count_uuid+1, wc )
data["UniqueID"] = Nbt.TAG_Long(struct.unpack('<q', new_uuid)[0])
data["Pos"] = location
key_actor = b''.join([b'actorprefix',new_actor_key_raw])
key_digp = self.build_digp_chunk_key(cx, cz)
nx,nz = block_coords_to_chunk_coords(location[0],location[2])
new_digp_key = self.build_digp_chunk_key(nx, nz)
if data.get("internalComponents") != None:
b_a = []
for b in struct.pack('>LL', actor_key[0], max_count_uuid+1 ):
b_a.append(Nbt.TAG_Byte(b))
tb_arry = Nbt.TAG_Byte_Array([b_a[0],b_a[1],b_a[2],b_a[3],b_a[4],b_a[5],b_a[6],b_a[7]])
data["internalComponents"]["EntityStorageKeyComponent"]["StorageKey"] = tb_arry
if self.world.level_wrapper.version >= (1, 18, 30, 4, 0):
try:
append_data_key_digp = self.level_db.get(new_digp_key)
except:
append_data_key_digp = b''
append_data_key_digp += new_actor_key_raw
self.level_db.put(new_digp_key, append_data_key_digp)
self.level_db.put(key_actor, Nbt.NBTFile(data).save_to(compressed=False, little_endian=True)
.replace(b'\x07\n\x00StorageKey\x08\x00\x00\x00', b'\x08\n\x00StorageKey\x08\x00'))
EntitiePlugin.Onmsgbox(self, "Copy", "Completed")
self._finishup(event)
else:
raw_chunk_entitie = Nbt.NBTFile(data).save_to(compressed=False, little_endian=True)
raw = self.world.level_wrapper.get_raw_chunk_data(nx, nz, self.canvas.dimension)
if raw.get(b'2'):
raw[b'2'] += raw_chunk_entitie
else:
raw[b'2'] = raw_chunk_entitie
self.world.level_wrapper.put_raw_chunk_data(nx,nz, raw, self.canvas.dimension)
EntitiePlugin.Onmsgbox(self, "Copy", "Completed")
self._finishup(event)
else:
cx, cz = block_coords_to_chunk_coords(data.get('Pos')[0], data.get('Pos')[2])
nx, nz = block_coords_to_chunk_coords(location[0], location[2])
actor_key = self.uuid_to_storage_key(data)
actor_key_raw = struct.pack('>LL', actor_key[0], actor_key[1])
uid = data.get("UniqueID").value
data["Pos"] = location
key_digp = self.build_digp_chunk_key(cx, cz)
new_digp_key = self.build_digp_chunk_key(nx, nz)
if self.world.level_wrapper.version >= (1, 18, 30, 4, 0):
if key_digp != new_digp_key:
dpkeys = self.level_db.get(key_digp)
try:
new_dpkeys = self.level_db.get(new_digp_key)
except:
new_dpkeys = b''
keep = []
new_dpkeys = b''.join([new_dpkeys, actor_key_raw])
for db in range(0, len(dpkeys), 8):
akey = dpkeys[db:db + 8]
if akey != actor_key_raw:
keep.append(akey)
dpkeys = b''.join(keep)
self.level_db.put(key_digp, dpkeys)
self.level_db.put(new_digp_key, new_dpkeys)
actor_key = b''.join([b'actorprefix', actor_key_raw])
self.level_db.put(actor_key, Nbt.NBTFile(data).save_to(compressed=False, little_endian=True)
.replace(b'\x07\n\x00StorageKey\x08\x00\x00\x00',
b'\x08\n\x00StorageKey\x08\x00'))
EntitiePlugin.Onmsgbox(self, "Move Position", "Completed")
self._finishup(event)
else:
if (cx,cz) != (nx,nz):
old_raw = self.world.level_wrapper.get_raw_chunk_data(cx,cz, self.canvas.dimension)
new_raw = self.world.level_wrapper.get_raw_chunk_data(nx,nz, self.canvas.dimension)
point = 0
max = len(old_raw[b'2'])
old_raw_keep = []
while point < max:
data_old, p = Nbt.load(old_raw[b'2'][point:],compressed=False, little_endian=True, offset=True)
point += p
if data.get('UniqueID') != data_old.get('UniqueID'):
old_raw_keep.append(data_old.save_to(compressed=False, little_endian=True))
old_raw[b'2'] = b''.join(old_raw_keep)
self.world.level_wrapper.put_raw_chunk_data(cx, cz, old_raw, self.canvas.dimension)
raw_chunk_entitie = Nbt.NBTFile(data).save_to(compressed=False, little_endian=True)
if new_raw.get(b'2'):
new_raw[b'2'] += raw_chunk_entitie
else:
new_raw[b'2'] = raw_chunk_entitie
self.world.level_wrapper.put_raw_chunk_data(nx, nz, new_raw, self.canvas.dimension)
EntitiePlugin.Onmsgbox(self, "Move Position", "Completed")
self._finishup(event)
else:
update_raw = self.world.level_wrapper.get_raw_chunk_data(nx, nz, self.canvas.dimension)
point = 0
max = len(update_raw[b'2'])
update_keep = []
while point < max:
data_old, p = Nbt.load(update_raw[b'2'][point:], compressed=False, little_endian=True,
offset=True)
point += p
if data.get('UniqueID') != data_old.get('UniqueID'):
update_keep.append(data_old.save_to(compressed=False, little_endian=True))
else:
update_keep.append(Nbt.NBTFile(data).save_to(compressed=False, little_endian=True))
update_raw[b'2'] = b''.join(update_keep)
self.world.level_wrapper.put_raw_chunk_data(nx, nz, update_raw, self.canvas.dimension)
EntitiePlugin.Onmsgbox(self, "Move Position", "Completed")
self._finishup(event)
def _finishup(self, event):
self.world.save()
self._set_list_of_actors_digp
self._load_entitie_data(event, False, False)
def _save_data_to_world(self, _):
NewRawB = b''
selection = self.ui_entitie_choice_list.GetSelection()
newData = self._snbt_edit_data.GetValue()
res = EntitiePlugin.important_question(self)
if res == False:
return
self.EntyData[selection] = Nbt.NBTFile(Nbt.from_snbt(newData)).to_snbt(1)
if self.world.level_wrapper.version >= (1, 18, 30, 4, 0):
for snbt, key in zip(self.EntyData, self.Key_tracker):
nbt = Nbt.from_snbt(snbt)
dim = struct.unpack("<i", self.get_dim_value())[0]
cx, cz = block_coords_to_chunk_coords(nbt.get('Pos')[0], nbt.get('Pos')[2])
try:
store_key = struct.unpack(">LL", (self._storage_key_(
nbt.get('internalComponents').get('EntityStorageKeyComponent').get('StorageKey'))))
except:
store_key = key
for key in self.digp.keys():
for i, p in enumerate(self.digp[key]):
if store_key == p:
self.digp[key].remove(p)
self.digp[(cx, cz, dim)].append(store_key)
raw_actor_key = b''.join([b'actorprefix', struct.pack('>II', store_key[0], store_key[1])])
raw_nbt_data = Nbt.NBTFile(nbt).save_to(compressed=False, little_endian=True) \
.replace(b'\x07\n\x00StorageKey\x08\x00\x00\x00', b'\x08\n\x00StorageKey\x08\x00')
self.level_db.put(raw_actor_key, raw_nbt_data)
for data in self.digp.keys():
cx, cz, dim = data
new_concatination_data = b''
if dim == 0:
raw_digp_key = b''.join([b'digp', struct.pack('<ii', cx, cz)])
else:
raw_digp_key = b''.join([b'digp', struct.pack('<iii', cx, cz, dim)])
for a, b in self.digp[data]:
new_concatination_data += struct.pack('>II', a, b)
self.level_db.put(raw_digp_key, new_concatination_data)
EntitiePlugin.Onmsgbox(self, "Entities Saved", "Complete")
else:
for snbt, key in zip(self.EntyData, self.Key_tracker):
nbt = Nbt.from_snbt(snbt)
dim = struct.unpack("<i", self.get_dim_value())[0]
cx, cz = block_coords_to_chunk_coords(nbt.get('Pos')[0], nbt.get('Pos')[2])
actor_key = self.uuid_to_storage_key(nbt)
self.actors[actor_key].clear()
self.actors[actor_key].append(nbt.to_snbt(1))
for k in self.digp.keys():
if actor_key in self.digp[k]:
self.digp[k].remove(actor_key)
self.digp[(cx, cz, dim)].append(actor_key)
for k, v in self.digp.items():
chunk = self.world.level_wrapper.get_raw_chunk_data(k[0], k[1], self.canvas.dimension)
chunk[b'2'] = b''
for ak in v:
nbt = Nbt.from_snbt(self.actors.get(ak)[0])
chunk[b'2'] += Nbt.NBTFile(nbt).save_to(compressed=False, little_endian=True)
self.world.level_wrapper.put_raw_chunk_data(k[0], k[1], chunk, self.canvas.dimension)
EntitiePlugin.Onmsgbox(self, "Entities Saved", "Complete")
def check_if_key_used(self, l, h):
pass
def build_actor_key(self, l, h):
return b''.join([b'actorprefix', struct.pack('>ii', l, h)])
def build_digp_chunk_key(self, xc, xz):
if 'minecraft:the_end' in self.canvas.dimension:
dim = int(2).to_bytes(4, 'little', signed=True)
elif 'minecraft:the_nether' in self.canvas.dimension:
dim = int(1).to_bytes(4, 'little', signed=True)
elif 'minecraft:overworld' in self.canvas.dimension:
dim = b''
return b''.join([b'digp', struct.pack('<ii', xc, xz), dim])
def digp_chunk_key_to_cords(self, data_key: bytes):
xc, zc = struct.unpack_from("<ii", data_key, 4)
if len(data_key) > 12:
dim = struct.unpack_from("<i", data_key, 12)[0]
return xc, zc, dim
else:
return xc, zc, 0
def check_if_duplicate(self, nbt_enty):
unique_id = nbt_enty.get('UniqueID')
if unique_id in self.all_uniqueids:
pass
def convert_uniqueids(self, uid_or_enty_cnt, world_counter=0):
l, h = 0, 0
world_cnt, cnt_enty = b'', b''
if isinstance(uid_or_enty_cnt, bytes):
l, h = struct.unpack('<II', uid_or_enty_cnt)
return l, h
elif isinstance(uid_or_enty_cnt, int):
cnt_enty = struct.pack('<I', uid_or_enty_cnt)
world_cnt = struct.pack('<I', world_counter)
return cnt_enty + world_cnt
def save_chunk_backup(self, cx, cz, dimension, chunk):
pathto = ""
fname = "chk_" + str(cx) + "_" + str(cz) + "_" + str(
dimension.replace(":", "_")) + "_Dont Remove first part.bak"
fdlg = wx.FileDialog(self, "Save Block Data", "", fname, "bakup files(*.bak)|*.*", wx.FD_SAVE)
fdlg.ShowModal()
pathto = fdlg.GetPath()
if ".bak" not in pathto:
pathto = pathto + ".bak"
with open(pathto, "wb") as tfile:
tfile.write(pickle.dumps(chunk))
tfile.close()
def load_chunk_backup(self):
chunk_raw = b''
fdlg = wx.FileDialog(self, "Load Block Data", "", "cx_cz_dimension_anyName.bak", "json files(*.bak)|*.*",
wx.FD_OPEN)
if fdlg.ShowModal() == wx.ID_OK:
pathto = fdlg.GetPath()
with open(pathto, "rb") as tfile:
chunk_raw = tfile.read()
tfile.close()
return chunk_raw
@property
def reuse_var(self):
self.lstOfE = []
# make sure to start fresh
self.selection = self.canvas.selection.selection_group
def get_dim_value(self):
if 'minecraft:the_end' in self.canvas.dimension:
dim = int(2).to_bytes(4, 'little', signed=True)
elif 'minecraft:the_nether' in self.canvas.dimension:
dim = int(1).to_bytes(4, 'little', signed=True)
elif 'minecraft:overworld' in self.canvas.dimension:
dim = int(0).to_bytes(4, 'little', signed=True)
return dim
def _load_entitie_data(self, event, bool1, bool2 ):
self.reuse_var
self._set_list_of_actors_digp
self.get_raw_data_new_version(bool1,bool2)
self.ui_entitie_choice_list.Set(self.lstOfE)
@property
def level_db(self):
level_wrapper = self.world.level_wrapper
if hasattr(level_wrapper, "level_db"):
return level_wrapper.level_db
else:
return level_wrapper._level_manager._db
def uuid_to_storage_key(self, nbt):
uid = nbt.get("UniqueID").value
uuid = struct.pack('<q', uid)
# "converted to Long to see real data"
acnt, wrldcnt = struct.unpack('<LL', uuid)
wc = 4294967296 - wrldcnt
actor_key = (wc, acnt)
return actor_key