-
Notifications
You must be signed in to change notification settings - Fork 15
/
Multi_Plugins.py
13600 lines (11755 loc) · 601 KB
/
Multi_Plugins.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
# 6 v
import urllib.request
import collections
import time
import copy
import zlib
import struct
import pickle
import uuid
import re
import wx
import math
from math import ceil
import numpy
import PyMCTranslate
from amulet_map_editor.api.opengl.camera import Projection
from amulet_map_editor.programs.edit.api.behaviour import BlockSelectionBehaviour
from amulet_map_editor.programs.edit.api.behaviour import StaticSelectionBehaviour
from amulet_map_editor.programs.edit.api.key_config import ACT_BOX_CLICK
from amulet_map_editor.programs.edit.api.events import (
EVT_SELECTION_CHANGE,
)
from typing import TYPE_CHECKING, Type, Any, Callable, Tuple, BinaryIO, Optional, Union, List
from amulet.utils import chunk_coords_to_region_coords
from amulet.utils import block_coords_to_chunk_coords
from amulet.level.formats.anvil_world.region import AnvilRegion
from amulet.level.formats.anvil_world.region import AnvilRegionInterface
from amulet.api.selection import SelectionGroup
from amulet.api.selection import SelectionBox
from amulet_map_editor.programs.edit.api.behaviour.pointer_behaviour import EVT_POINT_CHANGE
from amulet_map_editor.programs.edit.api.behaviour.pointer_behaviour import PointChangeEvent
from amulet_map_editor.programs.edit.api.behaviour.pointer_behaviour import PointerBehaviour
from amulet.api.data_types import PointCoordinates
from amulet_map_editor.programs.edit.api.events import (
InputPressEvent,
EVT_INPUT_PRESS,
)
from amulet_map_editor.programs.edit.api.operations import DefaultOperationUI
from amulet_map_editor.api.wx.ui.base_select import BaseSelect
from amulet_map_editor.api.wx.ui.block_select import BlockDefine
from amulet_map_editor.api.wx.ui.block_select import BlockSelect
from amulet.api.block import Block
from amulet.api.block_entity import BlockEntity
from amulet.api.errors import ChunkDoesNotExist
from amulet_map_editor.api.wx.ui import simple
from amulet_map_editor.api import image
from functools import partial, reduce
import operator
nbt_resources = image.nbt
from collections.abc import MutableMapping, MutableSequence
import abc
from amulet_nbt import *
import os
from os.path import exists
#import requests
from amulet_map_editor.api.wx.ui.block_select.properties import (
PropertySelect,
WildcardSNBTType,
EVT_PROPERTIES_CHANGE,
)
from amulet_map_editor.programs.edit.api.events import (
EVT_SELECTION_CHANGE,
)
if TYPE_CHECKING:
from amulet.api.level import BaseLevel
from amulet_map_editor.programs.edit.api.canvas import EditCanvas
def find_end_of_compounds(data):
def parse_compound(data, offset):
while offset < len(data):
tag_type = data[offset]
offset += 1
if tag_type == 0x00: # End of compound
break
name_length = int.from_bytes(data[offset:offset + 2], byteorder='little')
offset += 2 + name_length
offset = parse_tag(data, offset, tag_type)
return offset
def parse_tag(data, offset, tag_type):
size_map = {
0x01: 1, # Byte
0x02: 2, # Short
0x03: 4, # Int
0x04: 8, # Long
0x05: 4, # Float
0x06: 8, # Double
}
if tag_type in size_map:
offset += size_map[tag_type]
elif tag_type == 0x07: # Byte array
length = int.from_bytes(data[offset:offset + 4], byteorder='little')
offset += 4 + length
elif tag_type == 0x08: # String
length = int.from_bytes(data[offset:offset + 2], byteorder='little')
offset += 2 + length
elif tag_type == 0x09: # List
list_type = data[offset]
offset += 1
length = int.from_bytes(data[offset:offset + 4], byteorder='little')
offset += 4
for _ in range(length):
offset = parse_tag(data, offset, list_type)
elif tag_type == 0x0A: # Compound
offset = parse_compound(data, offset)
elif tag_type == 0x0B: # Int array
length = int.from_bytes(data[offset:offset + 4], byteorder='little')
offset += 4 + length * 4
elif tag_type == 0x0C: # Long array
length = int.from_bytes(data[offset:offset + 4], byteorder='little')
offset += 4 + length * 8
return offset
offset = 4
cnt = 0
num_compounds = int.from_bytes(data[:4], byteorder='little')
while offset < len(data):
if data[offset:offset + 3] == b'\x0A\x00\x00': # Start of a compound
offset = parse_compound(data, offset + 3)
cnt += 1
if cnt == num_compounds:
break
elif data[offset] == 0x00: # End of compounds
break
else:
raise ValueError("Invalid NBT data")
return offset
def block_enty_raw_cords(x, y, z): # fast search
data = CompoundTag({'x': IntTag(), 'y': IntTag(), 'z': IntTag()}).to_nbt(compressed=False, little_endian=True)
return data[3:-1]
def unpack_nbt_list(raw_nbt: bytes):
nbt_list = []
while raw_nbt:
read_context = ReadContext()
nbt = load(
raw_nbt,
little_endian=True,
read_context=read_context,
string_decoder=utf8_escape_decoder,
)
raw_nbt = raw_nbt[read_context.offset:]
nbt_list.append(nbt)
return nbt_list
def pack_nbt_list(nbt_list):
return b"".join(
[
nbt.save_to(
compressed=False,
little_endian=True,
string_encoder=utf8_escape_encoder,
)
for nbt in nbt_list
]
)
def create_new_actor_prefix(start, cnt):
actorKey = struct.pack('>LL', start, cnt)
db_key = b''.join([b'actorprefix', actorKey])
return db_key, actorKey
def uniqueid_to_actorprefix_key(UniqueID: LongTag):
packed_data = struct.pack('<q', UniqueID.py_data)
cnt, worldstartcnt = struct.unpack('<LL', packed_data)
start_cnt = 4294967296 - worldstartcnt
actorKey = struct.pack('>LL', start_cnt, cnt)
db_key = b''.join([b'actorprefix', actorKey])
return db_key
def _genorate_uid(cnt, worldstartcount):
start_c = worldstartcount
new_gen = struct.pack('<LL', int(cnt), int(start_c))
new_tag = LongTag(struct.unpack('<q', new_gen)[0])
return new_tag
def _storage_key_(val):
if isinstance(val, bytes):
return struct.unpack('>II', val)
if isinstance(val, StringTag):
return ByteArrayTag([x for x in val.py_data])
if isinstance(val, ByteArrayTag):
data = b''
for b in val: data += b
return data
def split_bytes(data):
return [data[i:i + 8] for i in range(0, len(data), 8)]
def get_y_range(test_val):
if test_val == struct.pack('<i', 1) or 'minecraft:the_nether' == test_val:
return (0, 127)
elif test_val == struct.pack('<i', 2) or 'minecraft:the_end' == test_val:
return (0, 255)
elif test_val == b'' or 'minecraft:overworld' == test_val:
return (-64, 319)
class ResetVaults():
def __init__(self, parent, canvas, world):
self.parent = parent
self.canvas = canvas
self.world = world
self.platform = self.world.level_wrapper.platform
self.progress = ProgressBar()
def reset_vaults(self):
chunks = self.world.all_chunk_coords(self.canvas.dimension)
total = len([c for c in chunks])
cnt = 0
for chunk in chunks:
cnt += 1
self.progress.progress_bar(total, cnt, title="Resetting all vaults", text="Chunk...")
cx, cz = chunk
if self.world.level_wrapper.platform == 'bedrock':
key = self.get_dim_chunkkey(cx, cz)
try:
self.level_db.delete(key + b'w')
except:
pass
try:
be_data = self.level_db.get(key + b"1")
nbt_data = unpack_nbt_list(be_data)
for d in nbt_data:
if "rewarded_players" in d.to_snbt():
print(d['data']['rewarded_players'].to_snbt())
d['data']['rewarded_players'] = ListTag([])
raw_list = pack_nbt_list(nbt_data)
self.level_db.put(key + b"1", raw_list)
except:
pass
else: #java
if self.world.has_chunk(cx, cz, self.canvas.dimension):
chunk = self.world.level_wrapper.get_raw_chunk_data(cx, cz, self.canvas.dimension)
if chunk.get('block_entities', None):
changed = False
for nbt in chunk['block_entities']:
if "vault" in nbt.to_snbt():
changed = True
nbt['server_data'].pop('rewarded_players', None)
if changed:
self.world.level_wrapper.put_raw_chunk_data(cx, cz, chunk, self.canvas.dimension)
wx.MessageBox("All Vaults should be reset.",
"INFO", wx.OK | wx.ICON_INFORMATION)
@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 get_dim_chunkkey(self, xx, zz):
chunkkey = b''
if 'minecraft:the_end' in self.canvas.dimension:
chunkkey = struct.pack('<iii', xx, zz, 2)
elif 'minecraft:the_nether' in self.canvas.dimension:
chunkkey = struct.pack('<iii', xx, zz, 1)
elif 'minecraft:overworld' in self.canvas.dimension:
chunkkey = struct.pack('<ii', xx, zz)
return chunkkey
class ChunkManager:
def __init__(self, parent=None, world=None, canvas=None):
self.parent = parent
self.canvas = canvas
self.world = world
self.chunks = None
self.platform = self.world.level_wrapper.platform
self.selection = None
self.org_key = None
self.last_offset_move = None
self.y_range = get_y_range(self.canvas.dimension)
self.chunk_and_entities = {}
self.all_chunks = None
if self.platform == 'bedrock':
self.world_start_count = self.get_current_entity_count()
self.next_slot = self.get_current_entity_count()
self.current_dim_key = self.get_dim_bytes()
def load_chunks(self):
self.selection = self.create_selection_map()
self.org_key = list(self.selection.keys())
self.last_offset_move = min((x, z) for x, z in self.org_key)
def the_chunks(self):
if self.parent._all_chunks.GetValue():
self.all_chunks = [x for x in self.world.level_wrapper.all_chunk_coords(self.canvas.dimension)]
else:
self.all_chunks = [x for x in self.canvas.selection.selection_group.chunk_locations()]
self.all_chunks = ((x, z) for x, z in self.all_chunks)
def get_chunk_data(self):
return copy.deepcopy(self.chunks)
def get_current_dim_key(self):
return self.current_dim_key
def set_current_dim_key(self, dim_key):
self.current_dim_key = dim_key
def create_selection_map(self):
if self.platform == 'bedrock':
selection_map = {
(x, z): SelectionBox((x * 16, self.y_range[0], z * 16), (x * 16 + 16, self.y_range[1], z * 16 + 16))
for k in self.chunks.keys() for x, z in [struct.unpack('<ii', k[0:8])]
}
return selection_map
else: # "java"
selection_map = {
(x, z): SelectionBox((x * 16, self.y_range[0], z * 16), (x * 16 + 16, self.y_range[1], z * 16 + 16))
for k in self.chunks.keys() for x, z in [k]
}
return selection_map
def outer_chunks(self, _range):
out_side_chunks = {}
inside = list(self.selection.keys())
surrounding_coords = []
_range -= 1
for xx, zz in self.selection.keys():
for i in range(xx - _range - 1, xx + _range + 2):
for j in range(zz - _range - 1, zz + _range + 2):
surrounding_coords.append((i, j))
for x, z in surrounding_coords:
if (x, z) not in inside:
out_side_chunks[(x, z)] = SelectionBox((x * 16, self.y_range[0], z * 16),
(x * 16 + 16, self.y_range[1], z * 16 + 16))
return out_side_chunks
def apply_selection(self):
tx, tz = self.last_offset_move
self.move_all_chunks_to(tx, tz)
self.org_key = list(self.selection.keys())
def move_all_chunks_to(self, target_x, target_z):
current_x, current_z = min((x, z) for x, z in self.org_key)
offset_x = target_x - current_x
offset_z = target_z - current_z
new_chunks = {}
if self.platform == 'bedrock':
for key in list(self.chunks.keys()):
x, z = struct.unpack('<ii', key[0:8])
new_x, new_z = x + offset_x, z + offset_z
new_key = struct.pack('<ii', new_x, new_z)
new_chunk_data = self.update_chunk_keys_entities(self.chunks[key].pop('chunk_data')
, new_key, new_x, new_z, x, z)
new_entitie_data = self.update_entities(self.chunks[key].pop('entitie')
, new_x, new_z)
new_chunks[new_key] = {'chunk_data': new_chunk_data, 'entitie': new_entitie_data,
'original_chunk_key': self.chunks[key].pop('original_chunk_key'),
'original_digp_actor_keys': self.chunks[key].pop('original_digp_actor_keys')}
else:
for key in list(self.chunks.keys()):
x, z = key
new_x, new_z = x + offset_x, z + offset_z
new_key = (new_x, new_z)
new_chunk_data = self.java_chunk(self.chunks[key].pop('chunk_data')
, new_key, new_x, new_z, x, z)
if self.chunks[key].get('entitie_data'):
new_entitie_data = self.java_entities(self.chunks[key].pop('entitie_data')
, new_key, new_x, new_z, x, z)
else:
new_entitie_data = None
new_chunks[new_key] = {'chunk_data': new_chunk_data, 'entitie_data': new_entitie_data}
self.chunks = new_chunks
if self.platform == 'java':
self.java_save()
else:
self.bedrock_save()
def java_entities(self, _chunk_entities, new_key, new_x, new_z, x, z):
chunk_entities = _chunk_entities
chunk_entities['Position'] = IntArrayTag([new_x, new_z])
for e in chunk_entities.get('Entities'):
x, y, z = e.get('Pos')
xc, zc = new_x * 16, new_z * 16
x_pos = x % 16
z_pos = z % 16
raw_pos_x = (x_pos + xc)
raw_pos_z = (z_pos + zc)
x, z = raw_pos_x, raw_pos_z
e['Pos'] = ListTag([DoubleTag(x), DoubleTag(y), DoubleTag(z)])
return chunk_entities
def java_chunk(self, _chunk_data, new_key, new_x, new_z, x, z):
chunk_data = _chunk_data
chunk_data['xPos'] = IntTag(new_x)
chunk_data['zPos'] = IntTag(new_z)
for be in chunk_data.get('block_entities'):
be['x'] = IntTag(new_x * 16)
be['z'] = IntTag(new_z * 16)
return chunk_data
def update_chunk_keys_entities(self, chunk_dict, new_key, new_x, new_z, x_old, z_old): # bedrock
dim = self.current_dim_key
new_dict = {}
for ik in list(chunk_dict.keys()):
# print(ik, dim)
if len(ik) == 10:
new_dict[new_key + ik[8:]] = chunk_dict.pop(ik)
elif 14 <= len(ik) <= 15:
new_dict[new_key][new_key + dim + ik[12:]] = chunk_dict.pop(ik)
elif ik[-1] == 64:
chunk_dict.pop(ik)
else:
main_key = int.to_bytes(ik[-1], 1, 'little')
if main_key == b'1':
nbt_data = unpack_nbt_list(chunk_dict[ik])
for be in nbt_data:
xc, zc = new_x * 16, new_z * 16
x_pos = be.tag['x'].py_int % 16
z_pos = be.tag['z'].py_int % 16
raw_pos_x = (x_pos + xc)
raw_pos_z = (z_pos + zc)
be.tag['x'] = IntTag(raw_pos_x)
be.tag['z'] = IntTag(raw_pos_z)
if be.get('pairlead'):
same_z = be.tag['pairz'].py_int // 16
same_x = be.tag['pairx'].py_int // 16
pairz = be.tag['pairz'].py_int % 16
pairx = be.tag['pairx'].py_int % 16
# Calculate the actual chunk positions of the pairs
pair_chunk_x = same_x - x_old + new_x
pair_chunk_z = same_z - z_old + new_z
# Adjust the chunk coordinates only if they are different
if same_x != x_old:
raw_pair_x = (pair_chunk_x * 16) + pairx
else:
raw_pair_x = raw_pos_x + (pairx - x_pos)
if same_z != z_old:
raw_pair_z = (pair_chunk_z * 16) + pairz
else:
raw_pair_z = raw_pos_z + (pairz - z_pos)
be.tag['pairx'] = IntTag(raw_pair_x)
be.tag['pairz'] = IntTag(raw_pair_z)
new_raw = pack_nbt_list(nbt_data)
new_dict[new_key + dim + main_key] = new_raw
else:
new_dict[new_key + dim + main_key] = chunk_dict.pop(ik)
return new_dict
def update_entities(self, entity_dict, new_x, new_z): # bedrock
new_dict = {}
new_digp = b''
new_digp_entry = {}
d = self.current_dim_key
chunk_id = struct.pack('<ii', new_x, new_z)
if entity_dict:
for digp_key, e in entity_dict.items():
for act, raw in e['actorprefix_dict'].items():
actor_nbt = load(raw, compressed=False, little_endian=True
, string_decoder=utf8_escape_decoder)
actor_pos = actor_nbt.get('Pos')
actor_nbt.pop('UniqueID')
actor_nbt.pop('internalComponents')
xc, zc = new_x * 16, new_z * 16
x_pos = (actor_pos[0]) % 16
z_pos = (actor_pos[2]) % 16
raw_pos_x = (x_pos + xc)
raw_pos_z = (z_pos + zc)
x, z = raw_pos_x, raw_pos_z
y = actor_pos[1]
actor_nbt.tag['Pos'] = ListTag([FloatTag(x),
FloatTag(y),
FloatTag(z)])
raw_nbt = actor_nbt.to_nbt(compressed=False, little_endian=True, string_encoder=utf8_escape_encoder)
actorprefix, digp_actor = create_new_actor_prefix(self.world_start_count, self.next_slot)
new_digp += digp_actor
new_dict[actorprefix] = raw_nbt
self.next_slot += 1
new_digp_entry[b'digp' + chunk_id + d] = {'digp_data': new_digp, 'actorprefix_dict': new_dict}
return new_digp_entry
else:
return {}
def move_all_selection_boxes(self, offset_x, offset_z):
current_x, current_z = self.last_offset_move
offset_xx = offset_x + current_x
offset_zz = offset_z + current_z
self.last_offset_move = (offset_xx, offset_zz)
new_selection = {}
for (x, z), selection_box in self.selection.items():
new_x, new_z = x + offset_x, z + offset_z
new_selection[(new_x, new_z)] = SelectionBox(
(new_x * 16, self.y_range[0], new_z * 16), (new_x * 16 + 16, self.y_range[1], new_z * 16 + 16)
)
self.selection = new_selection
def move_all_selection_boxes_to(self, target_x, target_z):
self.last_offset_move = (target_x, target_z)
current_x, current_z = min((x, z) for x, z in self.selection.keys())
offset_x = target_x - current_x
offset_z = target_z - current_z
new_selection = {}
for (x, z), selection_box in self.selection.items():
new_x, new_z = x + offset_x, z + offset_z
new_selection[(new_x, new_z)] = SelectionBox(
(new_x * 16, self.y_range[0], new_z * 16), (new_x * 16 + 16, self.y_range[1], new_z * 16 + 16)
)
self.selection = new_selection
def get_dim_bytes(self):
chunkkey = b''
if 'minecraft:the_end' in self.canvas.dimension:
chunkkey = struct.pack('<i', 2)
elif 'minecraft:the_nether' in self.canvas.dimension:
chunkkey = struct.pack('<i', 1)
elif 'minecraft:overworld' in self.canvas.dimension:
chunkkey = b''
return chunkkey
def get_dim_chunkkey(self, xx, zz):
chunkkey = b''
if 'minecraft:the_end' in self.canvas.dimension:
chunkkey = struct.pack('<iii', xx, zz, 2)
elif 'minecraft:the_nether' in self.canvas.dimension:
chunkkey = struct.pack('<iii', xx, zz, 1)
elif 'minecraft:overworld' in self.canvas.dimension:
chunkkey = struct.pack('<ii', xx, zz)
return chunkkey
def get_dim_vpath_java_dir(self, regonx, regonz, folder='region'): # entities
file = "r." + str(regonx) + "." + str(regonz) + ".mca"
path = self.world.level_wrapper.path
full_path = ''
dim = ''
if 'minecraft:the_end' in self.canvas.dimension:
dim = 'DIM1'
elif 'minecraft:the_nether' in self.canvas.dimension:
dim = 'DIM-1'
elif 'minecraft:overworld' in self.canvas.dimension:
dim = ''
full_path = os.path.join(path, dim, folder, file)
return full_path
def get_current_entity_count(self):
current_entites_values = []
world_count = self.world.level_wrapper.root_tag.get('worldStartCount')
start_count = 4294967294 - world_count
start_key = struct.pack('>L', start_count)
for k, v in self.world.level_wrapper.level_db.iterate(start=b'actorprefix' + start_key,
end=b'actorprefix' + start_key + b'\xff\xff\xff\xff'):
current_entites_values.append(int.from_bytes(k[15:], 'big'))
if len(current_entites_values) > 0:
return max(current_entites_values) + 1 # the next available slot for the last save
else:
return 0
@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 delete_outer(self, _):
chunk_values = list(self.outer_chunks(int(self.parent._select_outer_in.GetValue())).keys())
self.canvas.renderer.render_world.chunk_manager.unload()
self.canvas.renderer.render_world.unload()
for x, z in chunk_values:
self.canvas.world.level_wrapper.delete_chunk(x, z, self.canvas.dimension)
chunk_values_outer_chunks = list(self.outer_chunks(int(self.parent._select_outer_in.GetValue()) + 3).keys())
loaction_dict = collections.defaultdict(list)
if self.world.level_wrapper.platform == 'bedrock':
for xx, zz in chunk_values_outer_chunks:
chunkkey = self.get_dim_chunkkey(xx, zz)
self.level_db.delete(chunkkey + b'\x40')
else:
for xx, zz in chunk_values_outer_chunks:
rx, rz = chunk_coords_to_region_coords(xx, zz)
loaction_dict[(rx, rz)].append((xx, zz))
for rx, rz in loaction_dict.keys():
file_exists = exists(self.get_dim_vpath_java_dir(rx, rz))
if file_exists:
for di in loaction_dict[(rx, rz)]:
cx, cz = di
self.raw_data = AnvilRegion(self.get_dim_vpath_java_dir(rx, rz))
if self.raw_data.has_chunk(cx % 32, cz % 32):
nbtdata = self.raw_data.get_chunk_data(cx % 32, cz % 32)
if nbtdata['sections']:
nbtdata['Heightmaps'] = CompoundTag({})
nbtdata['blending_data'] = CompoundTag(
{"old_noise": ByteTag(1)})
nbtdata['DataVersion'] = IntTag(2860)
self.raw_data.put_chunk_data(cx % 32, cz % 32, nbtdata)
self.raw_data.save()
self.raw_data.unload()
self.world.save()
self.world.purge()
self.canvas.renderer.render_world.enable()
self.canvas.renderer.render_world.chunk_manager.rebuild()
def select_outer(self, _):
selection_values = list(self.outer_chunks(int(self.parent._select_outer_in.GetValue())).values())
merged = SelectionGroup(selection_values).merge_boxes()
self.canvas.selection.set_selection_group(merged)
def go_to_loaded(self, _):
selection_values = list(self.chunks_mg.selection.values())
location = selection_values[0].point_2
self.canvas.camera.set_location(location)
def move_north(self, _):
self.move_all_selection_boxes(0, -1)
new_selection = [v for v in self.selection.values()]
merged = SelectionGroup(new_selection).merge_boxes()
self.canvas.selection.set_selection_group(merged)
def move_south(self, _):
self.move_all_selection_boxes(0, 1)
new_selection = [v for v in self.selection.values()]
merged = SelectionGroup(new_selection).merge_boxes()
self.canvas.selection.set_selection_group(merged)
def move_east(self, _):
self.move_all_selection_boxes(1, 0)
new_selection = [v for v in self.selection.values()]
merged = SelectionGroup(new_selection).merge_boxes()
self.canvas.selection.set_selection_group(merged)
def move_west(self, _):
self.move_all_selection_boxes(-1, 0)
new_selection = [v for v in self.selection.values()]
merged = SelectionGroup(new_selection).merge_boxes()
self.canvas.selection.set_selection_group(merged)
def move_int_view(self, _):
cx, cy, cz = self.canvas.camera.location
self.move_all_selection_boxes_to(int(cx) // 16, int(cz) // 16)
new_selection = [v for v in self.selection.values()]
merged = SelectionGroup(new_selection).merge_boxes()
self.canvas.selection.set_selection_group(merged)
def renderer(self, _):
for c in self.chunks.keys():
if self.world.level_wrapper.platform == 'bedrock':
x, z = struct.unpack('<ii', c)
else:
x, z = c
if self.world.has_chunk(x, z, self.canvas.dimension):
self.world.get_chunk(x, z, self.canvas.dimension).changed = True
else:
self.world.create_chunk(x, z, self.canvas.dimension)
self.world.get_chunk(x, z, self.canvas.dimension).changed = True
self.world.save()
_min, _max = -4, 20
if self.world.level_wrapper.platform == 'bedrock':
if self.parent._range_top.GetValue() != "":
_max = int(self.parent._range_top.GetValue())
if self.parent._range_bottom.GetValue() != "":
_min = int(self.parent._range_bottom.GetValue())
for i, (c, v) in enumerate(self.chunks.items()):
if self.parent.include_blocks.GetValue():
for k, d in v["chunk_data"].items():
if len(k) == 14 or len(k) == 10:
if k[-2] == 47:
packed = struct.pack('B', k[-1])
signed_value = struct.unpack('b', packed)[0]
if _min <= signed_value <= _max:
self.level_db.put(k, d)
else:
self.level_db.put(k, d)
if self.parent.include_entities.GetValue():
for k, d in v["entitie"].items():
self.level_db.put(k, d['digp_data'])
for a, e in d['actorprefix_dict'].items():
self.level_db.put(a, e)
else: # java
region_file_ready = collections.defaultdict(list)
self.world.level_wrapper.root_tag['Data']['DataVersion'] = IntTag(2860)
self.world.level_wrapper.root_tag['Data']['Version'] = CompoundTag(
{"Snapshot": ByteTag(0), "Id": IntTag(2860),
"Name": StringTag("1.18.0")})
if self.parent._range_top.GetValue() != "":
_max = int(self.parent._range_top.GetValue())
if self.parent._range_bottom.GetValue() != "":
_min = int(self.parent._range_bottom.GetValue())
chunks = self.get_chunk_data()
for k, v in chunks.items():
x, z = k
rx, rz = chunk_coords_to_region_coords(x, z)
region_file_ready[(rx, rz)].append({(x, z): {'data': v}})
for r, v in region_file_ready.items():
rx, rz = r
if self.parent.include_entities.GetValue():
self.raw_data_entities = AnvilRegion(self.get_dim_vpath_java_dir(rx, rz, folder='entities'))
if self.parent.include_blocks.GetValue():
self.raw_data_chunks = AnvilRegion(self.get_dim_vpath_java_dir(rx, rz))
for items in v:
for c, d in items.items():
cx, cz = c
if self.parent.include_blocks.GetValue():
data = d['data'].get('chunk_data')
raw_chunk = self.raw_data_chunks.get_chunk_data(cx % 32, cz % 32)
old_sections = {}
old_be = {}
new_selection = {}
new_be = {}
for s in raw_chunk.get('sections'):
y_level = s['Y'].py_int
old_sections[y_level] = s
for be in raw_chunk.get('block_entities'):
y_level = be.get('y').py_int % 16
old_be[y_level] = be
for s in data.get('sections'):
y_level = s['Y'].py_int
new_selection[y_level] = s
for be in data.get('block_entities'):
y_level = be.get('y').py_int % 16
new_be[y_level] = be
for us in list(new_selection.keys()):
if not (_min <= us <= _max):
new_selection.pop(us, None)
for them in list(new_be.keys()):
if not (_min <= them <= _max):
new_be.pop(them, None)
# new_selection_ready = {**old_sections, **new_selection}
# new_be_ready = {**new_be, **old_be}
new_selection_ready = old_sections.copy()
for k, v in new_selection.items():
new_selection_ready[k] = v
new_be_ready = old_be.copy()
for k, v in new_be.items():
new_be_ready[k] = v
data['block_entities'] = ListTag([c for c in new_be_ready.values()])
# TODO add check box
data['sections'] = ListTag([c for c in new_selection_ready.values()])
data['DataVersion'] = IntTag(2860)
data['Heightmaps'] = CompoundTag({})
data['blending_data'] = CompoundTag(
{"old_noise": ByteTag(1)})
data.pop('isLightOn', None)
self.raw_data_chunks.put_chunk_data(cx % 32, cz % 32, data)
if self.parent.include_entities.GetValue():
if d['data'].get('entitie_data'):
data_e = d['data'].get('entitie_data')
for i, e in enumerate(data_e['Entities']):
data_e['Entities'][i]['UUID'] = IntArrayTag(
[x for x in struct.unpack('>iiii', uuid.uuid4().bytes)])
self.raw_data_entities.put_chunk_data(cx % 32, cz % 32, data_e)
if self.parent.include_entities.GetValue():
self.raw_data_entities.save()
self.raw_data_entities.unload()
if self.parent.include_blocks.GetValue():
self.raw_data_chunks.save()
self.raw_data_chunks.unload()
def save_loaded_chunks(self, _):
self.apply_selection()
self.canvas.renderer.render_world.chunk_manager.unload()
self.canvas.run_operation(lambda: self.renderer(_), "chunks", "Starting...")
self.world.purge()
self.canvas.renderer.render_world.chunk_manager.rebuild()
def bedrock_save(self):
self.the_chunks()
original_chunk_keys = {}
original_digp_actor_keys = {}
for xx, zz in self.all_chunks:
chunkkey = self.get_dim_chunkkey(xx, zz) # returns the bytes key for the current dimension
original_chunk_keys[(xx, zz)] = chunkkey
chunk_data = {}
entitiy_data = {}
new_digp_entry = {}
for k, v in self.world.level_wrapper.level_db.iterate(start=chunkkey,
end=chunkkey + b'\xff\xff\xff'):
if len(chunkkey) < 9:
chunk_data[k] = v
elif chunkkey == k[:12]:
chunk_data[k[:8]] = v
for k, v in self.world.level_wrapper.level_db.iterate(start=b'digp' + chunkkey[:-1],
end=b'digp' + chunkkey + b'\xff'):
if k == b'digp' + chunkkey and len(v) > 0:
digp_actor_list = []
actor_count = len(v) // 8
pnt = 0
for c in range(actor_count):
digp_actor_list.append(b'actorprefix' + v[pnt:pnt + 8])
raw_actor_nbt = self.level_db.get(b'actorprefix' + v[pnt:pnt + 8])
entitiy_data[b'actorprefix' + v[pnt:pnt + 8]] = raw_actor_nbt
pnt += 8
original_digp_actor_keys[b'digp' + chunkkey] = {'listed': digp_actor_list, 'original_bytes': v}
new_digp_entry[k] = {'digp_data': v, 'actorprefix_dict': entitiy_data}
self.chunk_and_entities[chunkkey] = {'chunk_data': chunk_data, 'entitie': new_digp_entry,
'original_chunk_key': chunkkey,
'original_digp_actor_keys': original_digp_actor_keys}
def java_save(self):
self.the_chunks()
original_chunk_keys = {}
loaction_dict = collections.defaultdict(list)
for xx, zz in self.all_chunks:
rx, rz = chunk_coords_to_region_coords(xx, zz)
loaction_dict[(rx, rz)].append((xx, zz))
for rx, rz in loaction_dict.keys():
file_exists_for_region = exists(self.get_dim_vpath_java_dir(rx, rz))
file_exists_for_entities = exists(self.get_dim_vpath_java_dir(rx, rz, folder='entities'))
if file_exists_for_region:
self.raw_data = AnvilRegion(self.get_dim_vpath_java_dir(rx, rz))
for di in loaction_dict[(rx, rz)]:
cx, cz = di
if self.raw_data.has_chunk(cx % 32, cz % 32):
nbtdata = self.raw_data.get_chunk_data(cx % 32, cz % 32)
self.chunk_and_entities[(cx, cz)] = {}
self.chunk_and_entities[(cx, cz)]['chunk_data'] = nbtdata
self.raw_data.unload()
if file_exists_for_entities:
self.raw_data = AnvilRegion(self.get_dim_vpath_java_dir(rx, rz, folder='entities'))
for di in loaction_dict[(rx, rz)]:
cx, cz = di
if self.raw_data.has_chunk(cx % 32, cz % 32):
nbtdata = self.raw_data.get_chunk_data(cx % 32, cz % 32)
self.chunk_and_entities[(cx, cz)]['entitie_data'] = nbtdata
self.raw_data.unload()
class ChunkSaveAndLoad(wx.Frame):
def __init__(self, parent, canvas, world):
super().__init__(parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=(560, 400), title="Position selections",
style=(
wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX | wx.RESIZE_BORDER | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX |
wx.CLIP_CHILDREN | wx.FRAME_FLOAT_ON_PARENT | wx.ALIGN_CENTER | wx.STAY_ON_TOP))
self.parent = parent
self.canvas = canvas
self.world = world
self.platform = self.world.level_wrapper.platform
self.chunks_mg = ChunkManager(parent=self, world=self.world, canvas=self.canvas)
self.has_been_loaded = False
self.raw_data_entities = None
self.raw_data_chunks = None
self.Freeze()
self.font = wx.Font(13, wx.FONTFAMILY_ROMAN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
self.SetFont(self.font)
self.SetForegroundColour((0, 255, 0))
self.SetBackgroundColour((0, 0, 0))
self.info_label = wx.StaticText(self, label="\nThis Directly edited the world ! "
"\n Make sure you have a backup! ")
self._all_chunks = wx.CheckBox(self, label="Save: All Chunks \n (can be slow)")
self._all_chunks.SetValue(False)
self._sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self._sizer)
self.main_sizer = wx.BoxSizer(wx.VERTICAL)
self.loaded_sizer = wx.BoxSizer(wx.VERTICAL)
self._sizer.Add(self.main_sizer)
self._sizer.Add(self.loaded_sizer)
self._save_button = wx.Button(self, label="Save Chunks")
self._save_button.Bind(wx.EVT_BUTTON, self.save_chunks)
self._load_button = wx.Button(self, label="Load Chunks")
self._load_button.Bind(wx.EVT_BUTTON, self.load_chunks)
self._move_chunks_into_view = wx.Button(self, label="Move Loaded Chunks \nInto Camera View", size=(180, 20))
self._go_to_loaded = wx.Button(self, label="Go to loaded chunks")
self._move_grid = wx.GridSizer(3, 3, 2, 1)
self._move_n = wx.Button(self, label="North")
self.space_1 = wx.StaticText(self, label="")
self.space_2 = wx.StaticText(self, label="")
self.space_3 = wx.StaticText(self, label="")
self.space_4 = wx.StaticText(self, label="")
self._move_s = wx.Button(self, label="South")
self._move_e = wx.Button(self, label="East")
self._move_w = wx.Button(self, label="West")
self._move_n.Bind(wx.EVT_BUTTON, self.chunks_mg.move_north)
self._move_s.Bind(wx.EVT_BUTTON, self.chunks_mg.move_south)
self._move_e.Bind(wx.EVT_BUTTON, self.chunks_mg.move_east)
self._move_w.Bind(wx.EVT_BUTTON, self.chunks_mg.move_west)
self._move_grid.Add(self.space_1)
self._move_grid.Add(self._move_n)
self._move_grid.Add(self.space_2)
self._move_grid.Add(self._move_w)
self._move_grid.Add(self.space_4)
self._move_grid.Add(self._move_e)
self._move_grid.Add(self.space_3)
self._move_grid.Add(self._move_s)
self.grid_for_outer = wx.GridSizer(2, 2, 5, 3)
self._select_outer_l = wx.StaticText(self, label=" Outer select / delete range:\n"
"(This is required for blending)")
self._select_outer_in = wx.TextCtrl(self, size=(40, 35))
self._select_outer_in.SetValue('2')
self._select_outer = wx.Button(self, label="Select Outer\n Chunks", size=(100, 35))
self._select_outer.Bind(wx.EVT_BUTTON, self.chunks_mg.select_outer)
self._delete_outer = wx.Button(self, label="Delete Outer\n Chunks", size=(100, 35))
self._delete_outer.Bind(wx.EVT_BUTTON, self.chunks_mg.delete_outer)
self.grid_for_outer.Add(self._select_outer_l)
self.grid_for_outer.Add(self._select_outer_in)
self.grid_for_outer.Add(self._delete_outer)
self.grid_for_outer.Add(self._select_outer)
self.l_range = wx.StaticText(self, label="Set Sub Chunk layer Range(min,max):")
self.l_min = wx.StaticText(self, label=" min:")
self.l_max = wx.StaticText(self, label=" max:")
self.l_range_Info = wx.StaticText(self, label="overworld=24, end=16, nether=8, Sub chunk is 16x16x16 \n"
"overworld range is -4 to 19, nether is 0 to 7 end is 0 to 15 ")
self._range_bottom = wx.TextCtrl(self, size=(40, 20))
self._range_top = wx.TextCtrl(self, size=(40, 20))
self._range_grid = wx.GridSizer(1, 4, 2, 0)
self._range_grid.Add(self.l_min)
self._range_grid.Add(self._range_bottom)
self._range_grid.Add(self.l_max)
self._range_grid.Add(self._range_top)
self._box_l_and_toggle = wx.BoxSizer(wx.HORIZONTAL)