-
Notifications
You must be signed in to change notification settings - Fork 194
/
Copy pathleveleditor.py
3782 lines (3023 loc) · 131 KB
/
leveleditor.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
"""Copyright (c) 2010-2012 David Rio Vierra
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE."""
import sys
from compass import CompassOverlay
from editortools.thumbview import ThumbView
from pymclevel.infiniteworld import SessionLockLost
"""
leveleditor.py
Viewport objects for Camera and Chunk views, which respond to some keyboard and
mouse input. LevelEditor object responds to some other keyboard and mouse
input, plus handles the undo stack and implements tile entity editors for
chests, signs, and more. Toolbar object which holds instances of EditorTool
imported from editortools/
"""
import gc
import os
import math
import csv
import copy
import time
import numpy
import config
import frustum
import logging
import glutils
import release
import mceutils
import platform
import functools
import editortools
import itertools
import mcplatform
import pymclevel
import renderer
from math import isnan
from os.path import dirname, isdir
from datetime import datetime, timedelta
from collections import defaultdict, deque
from OpenGL import GL
from OpenGL import GLU
from albow import alert, ask, AttrRef, Button, Column, get_font, Grid, input_text, IntField, Menu, root, Row, TableColumn, TableView, TextField, TimeField, Widget, CheckBox
from albow.controls import Label, SmallValueDisplay, ValueDisplay
from albow.dialogs import Dialog, QuickDialog, wrapped_label
from albow.openglwidgets import GLOrtho, GLViewport
from pygame import display, event, key, KMOD_ALT, KMOD_CTRL, KMOD_LALT, KMOD_META, KMOD_RALT, KMOD_SHIFT, mouse, MOUSEMOTION
from depths import DepthOffset
from editortools.operation import Operation
from editortools.chunk import GeneratorPanel
from glbackground import GLBackground, Panel
from glutils import gl, Texture
from mcplatform import askSaveFile
from pymclevel.minecraft_server import alphanum_key #?????
from renderer import MCRenderer
# Label = GLLabel
Settings = config.Settings("Settings")
Settings.flyMode = Settings("Fly Mode", False)
Settings.enableMouseLag = Settings("Enable Mouse Lag", False)
Settings.longDistanceMode = Settings("Long Distance Mode", False)
Settings.shouldResizeAlert = Settings("Window Size Alert", True)
Settings.closeMinecraftWarning = Settings("Close Minecraft Warning", True)
Settings.skin = Settings("MCEdit Skin", "[Current]")
Settings.fov = Settings("Field of View", 70.0)
Settings.spaceHeight = Settings("Space Height", 64)
Settings.blockBuffer = Settings("Block Buffer", 256 * 1048576)
Settings.reportCrashes = Settings("report crashes new", False)
Settings.reportCrashesAsked = Settings("report crashes asked", False)
Settings.viewDistance = Settings("View Distance", 8)
Settings.targetFPS = Settings("Target FPS", 30)
Settings.windowWidth = Settings("window width", 1024)
Settings.windowHeight = Settings("window height", 768)
Settings.windowX = Settings("window x", 0)
Settings.windowY = Settings("window y", 0)
Settings.windowShowCmd = Settings("window showcmd", 1)
Settings.setWindowPlacement = Settings("SetWindowPlacement", True)
Settings.showHiddenOres = Settings("show hidden ores", False)
Settings.fastLeaves = Settings("fast leaves", True)
Settings.roughGraphics = Settings("rough graphics", False)
Settings.showChunkRedraw = Settings("show chunk redraw", True)
Settings.drawSky = Settings("draw sky", True)
Settings.drawFog = Settings("draw fog", True)
Settings.showCeiling = Settings("show ceiling", True)
Settings.drawEntities = Settings("draw entities", True)
Settings.drawMonsters = Settings("draw monsters", True)
Settings.drawItems = Settings("draw items", True)
Settings.drawTileEntities = Settings("draw tile entities", True)
Settings.drawTileTicks = Settings("draw tile ticks", False)
Settings.drawUnpopulatedChunks = Settings("draw unpopulated chunks", True)
Settings.vertexBufferLimit = Settings("vertex buffer limit", 384)
Settings.vsync = Settings("vertical sync", 0)
Settings.visibilityCheck = Settings("visibility check", False)
Settings.viewMode = Settings("View Mode", "Camera")
Settings.undoLimit = Settings("Undo Limit", 20)
ControlSettings = config.Settings("Controls")
ControlSettings.mouseSpeed = ControlSettings("mouse speed", 5.0)
ControlSettings.cameraAccel = ControlSettings("camera acceleration", 125.0)
ControlSettings.cameraDrag = ControlSettings("camera drag", 100.0)
ControlSettings.cameraMaxSpeed = ControlSettings("camera maximum speed", 60.0)
ControlSettings.cameraBrakingSpeed = ControlSettings("camera braking speed", 8.0)
ControlSettings.invertMousePitch = ControlSettings("invert mouse pitch", False)
ControlSettings.autobrake = ControlSettings("autobrake", True)
ControlSettings.swapAxes = ControlSettings("swap axes looking down", False)
arch = platform.architecture()[0]
def remapMouseButton(button):
buttons = [0, 1, 3, 2, 4, 5] # mouse2 is right button, mouse3 is middle
if button < len(buttons):
return buttons[button]
return button
class ControlPanel(Panel):
@classmethod
def getHeader(cls):
header = Label("MCEdit {0} ({1})".format(release.release, arch), font=get_font(18, "VeraBd.ttf"))
return header
def __init__(self, editor):
Panel.__init__(self)
self.editor = editor
self.bg_color = (0, 0, 0, 0.8)
header = self.getHeader()
keysColumn = [Label("")]
buttonsColumn = [header]
cmd = mcplatform.cmd_name
hotkeys = ([(cmd + "-N", "Create New World", editor.mcedit.createNewWorld),
(cmd + "-O", "Open World...", editor.askOpenFile),
(cmd + "-L", "Load World...", editor.askLoadWorld),
(cmd + "-S", "Save", editor.saveFile),
(cmd + "-R", "Reload", editor.reload),
(cmd + "-W", "Close", editor.closeEditor),
("", "", lambda: None),
(cmd + "G", "Goto", editor.showGotoPanel),
(cmd + "-I", "World Info", editor.showWorldInfo),
(cmd + "-Z", "Undo", editor.undo),
(cmd + "-A", "Select All", editor.selectAll),
(cmd + "-D", "Deselect", editor.deselect),
(cmd + "-F", AttrRef(editor, 'viewDistanceLabelText'), editor.swapViewDistance),
("Alt-F4", "Quit", editor.quit),
])
if cmd == "Cmd":
hotkeys[-1] = ("Cmd-Q", hotkeys[-1][1], hotkeys[-1][2])
buttons = mceutils.HotkeyColumn(hotkeys, keysColumn, buttonsColumn)
sideColumn = editor.mcedit.makeSideColumn()
self.add(Row([buttons, sideColumn]))
self.shrink_wrap()
def key_down(self, evt):
if key.name(evt.key) == 'escape':
self.dismiss()
else:
self.editor.key_down(evt)
def mouse_down(self, e):
if e not in self:
self.dismiss()
def unproject(x, y, z):
try:
return GLU.gluUnProject(x, y, z)
except ValueError: # projection failed
return 0, 0, 0
def DebugDisplay(obj, *attrs):
col = []
for attr in attrs:
def _get(attr):
return lambda: str(getattr(obj, attr))
col.append(Row((Label(attr + " = "), ValueDisplay(width=600, get_value=_get(attr)))))
col = Column(col, align="l")
b = GLBackground()
b.add(col)
b.shrink_wrap()
return b
class CameraViewport(GLViewport):
anchor = "tlbr"
oldMousePosition = None
def __init__(self, editor):
self.editor = editor
rect = editor.mcedit.rect
GLViewport.__init__(self, rect)
near = 0.5
far = 4000.0
self.near = near
self.far = far
self.brake = False
self.lastTick = datetime.now()
# self.nearheight = near * tang
self.cameraPosition = (16., 45., 16.)
self.velocity = [0., 0., 0.]
self.yaw = -45. # degrees
self._pitch = 0.1
self.cameraVector = self._cameraVector()
# A state machine to dodge an apparent bug in pygame that generates erroneous mouse move events
# 0 = bad event already happened
# 1 = app just started or regained focus since last bad event
# 2 = mouse cursor was hidden after state 1, next event will be bad
self.avoidMouseJumpBug = 1
Settings.drawSky.addObserver(self)
Settings.drawFog.addObserver(self)
Settings.showCeiling.addObserver(self)
ControlSettings.cameraAccel.addObserver(self, "accelFactor")
ControlSettings.cameraMaxSpeed.addObserver(self, "maxSpeed")
ControlSettings.cameraBrakingSpeed.addObserver(self, "brakeMaxSpeed")
ControlSettings.invertMousePitch.addObserver(self)
ControlSettings.autobrake.addObserver(self)
ControlSettings.swapAxes.addObserver(self)
Settings.visibilityCheck.addObserver(self)
Settings.fov.addObserver(self, "fovSetting", callback=self.updateFov)
self.mouseVector = (0, 0, 0)
# self.add(DebugDisplay(self, "cameraPosition", "blockFaceUnderCursor", "mouseVector", "mouse3dPoint"))
@property
def pitch(self):
return self._pitch
@pitch.setter
def pitch(self, val):
self._pitch = min(89.999, max(-89.999, val))
def updateFov(self, val=None):
hfov = self.fovSetting
fov = numpy.degrees(2.0 * numpy.arctan(self.size[0] / self.size[1] * numpy.tan(numpy.radians(hfov) * 0.5)))
self.fov = fov
self.tang = numpy.tan(numpy.radians(fov))
def stopMoving(self):
self.velocity = [0, 0, 0]
def brakeOn(self):
self.brake = True
def brakeOff(self):
self.brake = False
tickInterval = 1000 / 30
oldPosition = (0, 0, 0)
flyMode = Settings.flyMode.configProperty()
def tickCamera(self, frameStartTime, inputs, inSpace):
if (frameStartTime - self.lastTick).microseconds > self.tickInterval * 1000:
timeDelta = frameStartTime - self.lastTick
self.lastTick = frameStartTime
else:
return
timeDelta = float(timeDelta.microseconds) / 1000000.
timeDelta = min(timeDelta, 0.125) # 8fps lower limit!
drag = ControlSettings.cameraDrag.get()
accel_factor = drag + ControlSettings.cameraAccel.get()
# if we're in space, move faster
drag_epsilon = 10.0 * timeDelta
max_speed = self.maxSpeed
if self.brake:
max_speed = self.brakeMaxSpeed
if inSpace:
accel_factor *= 3.0
max_speed *= 3.0
pi = self.editor.cameraPanKeys
mouseSpeed = ControlSettings.mouseSpeed.get()
self.yaw += pi[0] * mouseSpeed
self.pitch += pi[1] * mouseSpeed
alignMovementToAxes = key.get_mods() & KMOD_SHIFT
if self.flyMode:
(dx, dy, dz) = self._anglesToVector(self.yaw, 0)
elif self.swapAxesLookingDown or alignMovementToAxes:
p = self.pitch
if p > 80 or alignMovementToAxes:
p = 0
(dx, dy, dz) = self._anglesToVector(self.yaw, p)
else:
(dx, dy, dz) = self._cameraVector()
velocity = self.velocity # xxx learn to use matrix/vector libs
i = inputs
yaw = numpy.radians(self.yaw)
cosyaw = -numpy.cos(yaw)
sinyaw = numpy.sin(yaw)
if alignMovementToAxes:
cosyaw = int(cosyaw * 1.4)
sinyaw = int(sinyaw * 1.4)
dx = int(dx * 1.4)
dy = int(dy * 1.6)
dz = int(dz * 1.4)
directedInputs = mceutils.normalize((
i[0] * cosyaw + i[2] * dx,
i[1] + i[2] * dy,
i[2] * dz - i[0] * sinyaw,
))
# give the camera an impulse according to the state of the inputs and in the direction of the camera
cameraAccel = map(lambda x: x * accel_factor * timeDelta, directedInputs)
# cameraImpulse = map(lambda x: x*impulse_factor, directedInputs)
newVelocity = map(lambda a, b: a + b, velocity, cameraAccel)
velocityDir, speed = mceutils.normalize_size(newVelocity)
# apply drag
if speed:
if self.autobrake and not any(inputs):
speed = 0.15 * speed
else:
sign = speed / abs(speed)
speed = abs(speed)
speed = speed - (drag * timeDelta)
if speed < 0.0:
speed = 0.0
speed *= sign
speed = max(-max_speed, min(max_speed, speed))
if abs(speed) < drag_epsilon:
speed = 0
velocity = map(lambda a: a * speed, velocityDir)
# velocity = map(lambda p,d: p + d, velocity, cameraImpulse)
d = map(lambda a, b: abs(a - b), self.cameraPosition, self.oldPosition)
if d[0] + d[2] > 32.0:
self.oldPosition = self.cameraPosition
self.updateFloorQuad()
self.cameraPosition = map(lambda p, d: p + d * timeDelta, self.cameraPosition, velocity)
if self.cameraPosition[1] > 3800.:
self.cameraPosition[1] = 3800.
if self.cameraPosition[1] < -1000.:
self.cameraPosition[1] = -1000.
self.velocity = velocity
self.cameraVector = self._cameraVector()
self.editor.renderer.position = self.cameraPosition
if self.editor.currentTool.previewRenderer:
self.editor.currentTool.previewRenderer.position = self.cameraPosition
def setModelview(self):
pos = self.cameraPosition
look = numpy.array(self.cameraPosition)
look += self.cameraVector
up = (0, 1, 0)
GLU.gluLookAt(pos[0], pos[1], pos[2],
look[0], look[1], look[2],
up[0], up[1], up[2])
def _cameraVector(self):
return self._anglesToVector(self.yaw, self.pitch)
def _anglesToVector(self, yaw, pitch):
def nanzero(x):
if isnan(x):
return 0
else:
return x
dx = -math.sin(math.radians(yaw)) * math.cos(math.radians(pitch))
dy = -math.sin(math.radians(pitch))
dz = math.cos(math.radians(yaw)) * math.cos(math.radians(pitch))
return map(nanzero, [dx, dy, dz])
def updateMouseVector(self):
self.mouseVector = self._mouseVector()
def _mouseVector(self):
"""
returns a vector reflecting a ray cast from the camera
position to the mouse position on the near plane
"""
x, y = mouse.get_pos()
# if (x, y) not in self.rect:
# return (0, 0, 0); # xxx
y = self.get_root().height - y
point1 = unproject(x, y, 0.0)
point2 = unproject(x, y, 1.0)
v = numpy.array(point2) - point1
v = mceutils.normalize(v)
return v
def _blockUnderCursor(self, center=False):
"""
returns a point in 3d space that was determined by
reading the depth buffer value
"""
try:
GL.glReadBuffer(GL.GL_BACK)
except Exception:
logging.exception('Exception during glReadBuffer')
ws = self.get_root().size
if center:
x, y = ws
x //= 2
y //= 2
else:
x, y = mouse.get_pos()
if (x < 0 or y < 0 or x >= ws[0] or
y >= ws[1]):
return 0, 0, 0
y = ws[1] - y
try:
pixel = GL.glReadPixels(x, y, 1, 1, GL.GL_DEPTH_COMPONENT, GL.GL_FLOAT)
newpoint = unproject(x, y, pixel[0])
except Exception:
return 0, 0, 0
return newpoint
def updateBlockFaceUnderCursor(self):
focusPair = None
if not self.enableMouseLag or self.editor.frames & 1:
self.updateMouseVector()
if self.editor.mouseEntered:
if not self.mouseMovesCamera:
mouse3dPoint = self._blockUnderCursor()
focusPair = self.findBlockFaceUnderCursor(mouse3dPoint)
elif self.editor.longDistanceMode:
mouse3dPoint = self._blockUnderCursor(True)
focusPair = self.findBlockFaceUnderCursor(mouse3dPoint)
# otherwise, find the block at a controllable distance in front of the camera
if focusPair is None:
focusPair = (self.getCameraPoint(), (0, 0, 0))
self.blockFaceUnderCursor = focusPair
def findBlockFaceUnderCursor(self, projectedPoint):
"""Returns a (pos, Face) pair or None if one couldn't be found"""
d = [0, 0, 0]
try:
intProjectedPoint = map(int, map(numpy.floor, projectedPoint))
except ValueError:
return None # catch NaNs
intProjectedPoint[1] = max(0, intProjectedPoint[1])
# find out which face is under the cursor. xxx do it more precisely
faceVector = ((projectedPoint[0] - (intProjectedPoint[0] + 0.5)),
(projectedPoint[1] - (intProjectedPoint[1] + 0.5)),
(projectedPoint[2] - (intProjectedPoint[2] + 0.5))
)
av = map(abs, faceVector)
i = av.index(max(av))
delta = faceVector[i]
if delta < 0:
d[i] = -1
else:
d[i] = 1
potentialOffsets = []
try:
block = self.editor.level.blockAt(*intProjectedPoint)
except (EnvironmentError, pymclevel.ChunkNotPresent):
return intProjectedPoint, d
if block == pymclevel.alphaMaterials.SnowLayer.ID:
potentialOffsets.append((0, 1, 0))
else:
# discard any faces that aren't likely to be exposed
for face, offsets in pymclevel.faceDirections:
point = map(lambda a, b: a + b, intProjectedPoint, offsets)
try:
neighborBlock = self.editor.level.blockAt(*point)
if block != neighborBlock:
potentialOffsets.append(offsets)
except (EnvironmentError, pymclevel.ChunkNotPresent):
pass
# check each component of the face vector to see if that face is exposed
if tuple(d) not in potentialOffsets:
av[i] = 0
i = av.index(max(av))
d = [0, 0, 0]
delta = faceVector[i]
if delta < 0:
d[i] = -1
else:
d[i] = 1
if tuple(d) not in potentialOffsets:
av[i] = 0
i = av.index(max(av))
d = [0, 0, 0]
delta = faceVector[i]
if delta < 0:
d[i] = -1
else:
d[i] = 1
if tuple(d) not in potentialOffsets:
if len(potentialOffsets):
d = potentialOffsets[0]
else:
# use the top face as a fallback
d = [0, 1, 0]
return intProjectedPoint, d
@property
def ratio(self):
return self.width / float(self.height)
startingMousePosition = None
def mouseLookOn(self):
root.get_root().capture_mouse(self)
self.focus_switch = None
self.startingMousePosition = mouse.get_pos()
if self.avoidMouseJumpBug == 1:
self.avoidMouseJumpBug = 2
def mouseLookOff(self):
root.get_root().capture_mouse(None)
if self.startingMousePosition:
mouse.set_pos(*self.startingMousePosition)
self.startingMousePosition = None
@property
def mouseMovesCamera(self):
return root.get_root().captured_widget is not None
def toggleMouseLook(self):
if not self.mouseMovesCamera:
self.mouseLookOn()
else:
self.mouseLookOff()
mobs = pymclevel.Entity.monsters + ["[Custom]"]
@mceutils.alertException
def editMonsterSpawner(self, point):
mobs = self.mobs
tileEntity = self.editor.level.tileEntityAt(*point)
if not tileEntity:
tileEntity = pymclevel.TAG_Compound()
tileEntity["id"] = pymclevel.TAG_String("MobSpawner")
tileEntity["x"] = pymclevel.TAG_Int(point[0])
tileEntity["y"] = pymclevel.TAG_Int(point[1])
tileEntity["z"] = pymclevel.TAG_Int(point[2])
tileEntity["Delay"] = pymclevel.TAG_Short(120)
tileEntity["EntityId"] = pymclevel.TAG_String(mobs[0])
self.editor.level.addTileEntity(tileEntity)
self.editor.addUnsavedEdit()
panel = Dialog()
def addMob(id):
if id not in mobs:
mobs.insert(0, id)
mobTable.selectedIndex = 0
def selectTableRow(i, evt):
if mobs[i] == "[Custom]":
id = input_text("Type in an EntityID for this spawner. Invalid IDs may crash Minecraft.", 150)
if id:
addMob(id)
else:
return
mobTable.selectedIndex = mobs.index(id)
else:
mobTable.selectedIndex = i
if evt.num_clicks == 2:
panel.dismiss()
mobTable = TableView(columns=(
TableColumn("", 200),
)
)
mobTable.num_rows = lambda: len(mobs)
mobTable.row_data = lambda i: (mobs[i],)
mobTable.row_is_selected = lambda x: x == mobTable.selectedIndex
mobTable.click_row = selectTableRow
mobTable.selectedIndex = 0
def selectedMob():
return mobs[mobTable.selectedIndex]
id = tileEntity["EntityId"].value
addMob(id)
mobTable.selectedIndex = mobs.index(id)
choiceCol = Column((ValueDisplay(width=200, get_value=lambda: selectedMob() + " spawner"), mobTable))
okButton = Button("OK", action=panel.dismiss)
panel.add(Column((choiceCol, okButton)))
panel.shrink_wrap()
panel.present()
tileEntity["EntityId"] = pymclevel.TAG_String(selectedMob())
@mceutils.alertException
def editSign(self, point):
block = self.editor.level.blockAt(*point)
tileEntity = self.editor.level.tileEntityAt(*point)
linekeys = ["Text" + str(i) for i in range(1, 5)]
if not tileEntity:
tileEntity = pymclevel.TAG_Compound()
tileEntity["id"] = pymclevel.TAG_String("Sign")
tileEntity["x"] = pymclevel.TAG_Int(point[0])
tileEntity["y"] = pymclevel.TAG_Int(point[1])
tileEntity["z"] = pymclevel.TAG_Int(point[2])
for l in linekeys:
tileEntity[l] = pymclevel.TAG_String("")
self.editor.level.addTileEntity(tileEntity)
panel = Dialog()
lineFields = [TextField(width=150) for l in linekeys]
for l, f in zip(linekeys, lineFields):
f.value = tileEntity[l].value
colors = [
"Black",
"Blue",
"Green",
"Cyan",
"Red",
"Purple",
"Yellow",
"Light Gray",
"Dark Gray",
"Light Blue",
"Bright Green",
"Bright Blue",
"Bright Red",
"Bright Purple",
"Bright Yellow",
"White",
]
def menu_picked(index):
c = u'\xa7' + hex(index)[-1]
currentField = panel.focus_switch.focus_switch
currentField.text += c # xxx view hierarchy
currentField.insertion_point = len(currentField.text)
colorMenu = mceutils.MenuButton("Color Code...", colors, menu_picked=menu_picked)
column = [Label("Edit Sign")] + lineFields + [colorMenu, Button("OK", action=panel.dismiss)]
panel.add(Column(column))
panel.shrink_wrap()
if panel.present():
self.editor.addUnsavedEdit()
for l, f in zip(linekeys, lineFields):
tileEntity[l].value = f.value[:15]
@mceutils.alertException
def editContainer(self, point, containerID):
tileEntityTag = self.editor.level.tileEntityAt(*point)
if tileEntityTag is None:
tileEntityTag = pymclevel.TileEntity.Create(containerID)
pymclevel.TileEntity.setpos(tileEntityTag, point)
self.editor.level.addTileEntity(tileEntityTag)
if tileEntityTag["id"].value != containerID:
return
backupEntityTag = copy.deepcopy(tileEntityTag)
def itemProp(key):
# xxx do validation here
def getter(self):
if 0 == len(tileEntityTag["Items"]):
return "N/A"
return tileEntityTag["Items"][self.selectedItemIndex][key].value
def setter(self, val):
if 0 == len(tileEntityTag["Items"]):
return
self.dirty = True
tileEntityTag["Items"][self.selectedItemIndex][key].value = val
return property(getter, setter)
class ChestWidget(Widget):
dirty = False
Slot = itemProp("Slot")
id = itemProp("id")
Damage = itemProp("Damage")
Count = itemProp("Count")
itemLimit = pymclevel.TileEntity.maxItems.get(containerID, 255)
def slotFormat(slot):
slotNames = pymclevel.TileEntity.slotNames.get(containerID)
if slotNames:
return slotNames.get(slot, slot)
return slot
chestWidget = ChestWidget()
chestItemTable = TableView(columns=[
TableColumn("Slot", 80, "l", fmt=slotFormat),
TableColumn("ID", 50, "l"),
TableColumn("DMG", 50, "l"),
TableColumn("Count", 65, "l"),
TableColumn("Name", 200, "l"),
])
def itemName(id, damage):
try:
return pymclevel.items.items.findItem(id, damage).name
except pymclevel.items.ItemNotFound:
return "Unknown Item"
def getRowData(i):
item = tileEntityTag["Items"][i]
slot, id, damage, count = item["Slot"].value, item["id"].value, item["Damage"].value, item["Count"].value
return slot, id, damage, count, itemName(id, damage)
chestWidget.selectedItemIndex = 0
def selectTableRow(i, evt):
chestWidget.selectedItemIndex = i
chestItemTable.num_rows = lambda: len(tileEntityTag["Items"])
chestItemTable.row_data = getRowData
chestItemTable.row_is_selected = lambda x: x == chestWidget.selectedItemIndex
chestItemTable.click_row = selectTableRow
fieldRow = (
# mceutils.IntInputRow("Slot: ", ref=AttrRef(chestWidget, 'Slot'), min= -128, max=127),
mceutils.IntInputRow("ID: ", ref=AttrRef(chestWidget, 'id'), min=0, max=32767),
mceutils.IntInputRow("DMG: ", ref=AttrRef(chestWidget, 'Damage'), min=-32768, max=32767),
mceutils.IntInputRow("Count: ", ref=AttrRef(chestWidget, 'Count'), min=-128, max=127),
)
def deleteFromWorld():
i = chestWidget.selectedItemIndex
item = tileEntityTag["Items"][i]
id = item["id"].value
Damage = item["Damage"].value
deleteSameDamage = mceutils.CheckBoxLabel("Only delete items with the same damage value")
deleteBlocksToo = mceutils.CheckBoxLabel("Also delete blocks placed in the world")
if id not in (8, 9, 10, 11): # fluid blocks
deleteBlocksToo.value = True
w = wrapped_label("WARNING: You are about to modify the entire world. This cannot be undone. Really delete all copies of this item from all land, chests, furnaces, dispensers, dropped items, item-containing tiles, and player inventories in this world?", 60)
col = (w, deleteSameDamage)
if id < 256:
col += (deleteBlocksToo,)
d = Dialog(Column(col), ["OK", "Cancel"])
if d.present() == "OK":
def deleteItemsIter():
i = 0
if deleteSameDamage.value:
def matches(t):
return t["id"].value == id and t["Damage"].value == Damage
else:
def matches(t):
return t["id"].value == id
def matches_itementity(e):
if e["id"].value != "Item":
return False
if "Item" not in e:
return False
t = e["Item"]
return matches(t)
for player in self.editor.level.players:
tag = self.editor.level.getPlayerTag(player)
l = len(tag["Inventory"])
tag["Inventory"].value = [t for t in tag["Inventory"].value if not matches(t)]
for chunk in self.editor.level.getChunks():
if id < 256 and deleteBlocksToo.value:
matchingBlocks = chunk.Blocks == id
if deleteSameDamage.value:
matchingBlocks &= chunk.Data == Damage
if any(matchingBlocks):
chunk.Blocks[matchingBlocks] = 0
chunk.Data[matchingBlocks] = 0
chunk.chunkChanged()
self.editor.invalidateChunks([chunk.chunkPosition])
for te in chunk.TileEntities:
if "Items" in te:
l = len(te["Items"])
te["Items"].value = [t for t in te["Items"].value if not matches(t)]
if l != len(te["Items"]):
chunk.dirty = True
entities = [e for e in chunk.Entities if matches_itementity(e)]
if len(entities) != len(chunk.Entities):
chunk.Entities.value = entities
chunk.dirty = True
yield (i, self.editor.level.chunkCount)
i += 1
progressInfo = "Deleting the item {0} from the entire world ({1} chunks)".format(itemName(chestWidget.id, 0), self.editor.level.chunkCount)
mceutils.showProgress(progressInfo, deleteItemsIter(), cancel=True)
self.editor.addUnsavedEdit()
chestWidget.selectedItemIndex = min(chestWidget.selectedItemIndex, len(tileEntityTag["Items"]) - 1)
def deleteItem():
i = chestWidget.selectedItemIndex
item = tileEntityTag["Items"][i]
tileEntityTag["Items"].value = [t for t in tileEntityTag["Items"].value if t is not item]
chestWidget.selectedItemIndex = min(chestWidget.selectedItemIndex, len(tileEntityTag["Items"]) - 1)
def deleteEnable():
return len(tileEntityTag["Items"]) and chestWidget.selectedItemIndex != -1
def addEnable():
return len(tileEntityTag["Items"]) < chestWidget.itemLimit
def addItem():
slot = 0
for item in tileEntityTag["Items"]:
if slot == item["Slot"].value:
slot += 1
if slot >= chestWidget.itemLimit:
return
item = pymclevel.TAG_Compound()
item["id"] = pymclevel.TAG_Short(0)
item["Damage"] = pymclevel.TAG_Short(0)
item["Slot"] = pymclevel.TAG_Byte(slot)
item["Count"] = pymclevel.TAG_Byte(0)
tileEntityTag["Items"].append(item)
addItemButton = Button("Add Item", action=addItem, enable=addEnable)
deleteItemButton = Button("Delete This Item", action=deleteItem, enable=deleteEnable)
deleteFromWorldButton = Button("Delete Item ID From Entire World", action=deleteFromWorld, enable=deleteEnable)
deleteCol = Column((addItemButton, deleteItemButton, deleteFromWorldButton), align="l")
fieldRow = Row(fieldRow)
col = Column((chestItemTable, fieldRow, deleteCol))
chestWidget.add(col)
chestWidget.shrink_wrap()
Dialog(client=chestWidget, responses=["Done"]).present()
level = self.editor.level
class ChestEditOperation(Operation):
def perform(self, recordUndo=True):
level.addTileEntity(tileEntityTag)
def undo(self):
level.addTileEntity(backupEntityTag)
return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntityTag), (1, 1, 1))
if chestWidget.dirty:
op = ChestEditOperation(self.editor, self.editor.level)
op.perform()
self.editor.addOperation(op)
self.editor.addUnsavedEdit()
rightMouseDragStart = None
def rightClickDown(self, evt):
self.rightMouseDragStart = datetime.now()
self.toggleMouseLook()
def rightClickUp(self, evt):
x, y = evt.pos
if self.rightMouseDragStart is None:
return
td = datetime.now() - self.rightMouseDragStart
# except AttributeError:
# return
# print "RightClickUp: ", td
if td.seconds > 0 or td.microseconds > 280000:
self.mouseLookOff()
def leftClickDown(self, evt):
self.editor.toolMouseDown(evt, self.blockFaceUnderCursor)
if evt.num_clicks == 2:
def distance2(p1, p2):
return numpy.sum(map(lambda a, b: (a - b) ** 2, p1, p2))
point, face = self.blockFaceUnderCursor
if point is not None:
point = map(lambda x: int(numpy.floor(x)), point)
if self.editor.currentTool is self.editor.selectionTool:
try:
block = self.editor.level.blockAt(*point)
if distance2(point, self.cameraPosition) > 4:
blockEditors = {
pymclevel.alphaMaterials.MonsterSpawner.ID: self.editMonsterSpawner,
pymclevel.alphaMaterials.Sign.ID: self.editSign,
pymclevel.alphaMaterials.WallSign.ID: self.editSign,
}
edit = blockEditors.get(block)
if edit:
self.editor.endSelection()
edit(point)
else:
# detect "container" tiles
te = self.editor.level.tileEntityAt(*point)
if te and "Items" in te and "id" in te:
self.editor.endSelection()
self.editContainer(point, te["id"].value)
except (EnvironmentError, pymclevel.ChunkNotPresent):
pass
def leftClickUp(self, evt):
self.editor.toolMouseUp(evt, self.blockFaceUnderCursor)
# --- Event handlers ---
def mouse_down(self, evt):
button = remapMouseButton(evt.button)
logging.debug("Mouse down %d @ %s", button, evt.pos)
if button == 1:
if sys.platform == "darwin" and evt.ctrl:
self.rightClickDown(evt)
else:
self.leftClickDown(evt)
elif button == 2: