repo_id
stringclasses
383 values
file_path
stringlengths
7
168
content
stringlengths
0
1.75M
Amulet-Map-Editor
amulet_map_editor\api\opengl\resource_pack\resource_pack_manager.py
from amulet_map_editor.api.opengl.resource_pack import OpenGLResourcePack class OpenGLResourcePackManagerStatic: """A class to hold an opengl resource pack. All classes wanting to access block geometry or textures should subclass this class. """ def __init__( self, resource_pack: OpenGLResourcePack, ): self._resource_pack = resource_pack @property def resource_pack(self) -> OpenGLResourcePack: return self._resource_pack class OpenGLResourcePackManager(OpenGLResourcePackManagerStatic): """A class to hold and enable switching of an opengl resource pack. All classes wanting to access block geometry or textures should subclass this class. """ @property def resource_pack(self) -> OpenGLResourcePack: return self._resource_pack @resource_pack.setter def resource_pack(self, resource_pack: OpenGLResourcePack): assert isinstance(resource_pack, OpenGLResourcePack) self._resource_pack = resource_pack self._rebuild() def _rebuild(self): """Rebuild all geometry.""" raise NotImplementedError
Amulet-Map-Editor
amulet_map_editor\api\opengl\resource_pack\__init__.py
from .resource_pack import OpenGLResourcePack from .resource_pack_manager import ( OpenGLResourcePackManager, OpenGLResourcePackManagerStatic, )
Amulet-Map-Editor
amulet_map_editor\api\opengl\shaders\__init__.py
from OpenGL.GL import ( glClearColor, glBindVertexArray, glGenVertexArrays, GL_VERTEX_SHADER, GL_FRAGMENT_SHADER, glGetString, GL_SHADING_LANGUAGE_VERSION, GL_VERSION, ) import OpenGL.GL.shaders import os from typing import Dict, Tuple, Any import re shader_dir = os.path.join(os.path.dirname(__file__)) _shaders: Dict[Tuple[str, str], Any] = {} GL_VERSION_MATCH = re.compile(r"^(?P<major>\d+)\.(?P<minor>\d+)?") def get_shader( context_identifier: str, shader_name: str ) -> OpenGL.GL.shaders.ShaderProgram: """ Get the specified shader program. This must be called from the same thread that initialised the context :param context_identifier: The identifier for the context :param shader_name: The name of the shader to load :return: The shader program """ shader_key = (context_identifier, shader_name) if shader_key not in _shaders: gl_version_match = GL_VERSION_MATCH.match( glGetString(GL_SHADING_LANGUAGE_VERSION).decode("utf-8") ) if gl_version_match: gl_version_tuple = tuple(int(v) for v in gl_version_match.groups()) if gl_version_tuple >= (3, 30): gl_version = "330" # opengl 3.3 else: gl_version = "120" # opengl 2.1 else: # in theory this shouldn't happen if the version is correctly formatted. gl_version = "330" def compile_shader(): return OpenGL.GL.shaders.compileProgram( _load_shader( os.path.join(shader_dir, f"{shader_name}_{gl_version}.vert"), GL_VERTEX_SHADER, ), _load_shader( os.path.join(shader_dir, f"{shader_name}_{gl_version}.frag"), GL_FRAGMENT_SHADER, ), ) try: shader = compile_shader() except ( OpenGL.GL.shaders.ShaderValidationError ): # on Mac the above fails if there is no VBO bound glBindVertexArray(glGenVertexArrays(1)) shader = compile_shader() glBindVertexArray(0) _shaders[shader_key] = shader return _shaders[shader_key] def _load_shader(shader_path, shader_type): with open(shader_path, "rb") as f: shader = f.read() return OpenGL.GL.shaders.compileShader(shader, shader_type)
Amulet-Map-Editor
amulet_map_editor\api\opengl\mesh\level\level.py
from typing import TYPE_CHECKING, Generator, Optional, Any import numpy import time import logging from amulet.api.data_types import Dimension, ChunkCoordinates from .chunk import RenderChunk from .region import ChunkManager from .selection import GreenRenderSelectionGroup from amulet_map_editor.api.opengl.data_types import ( CameraLocationType, CameraRotationType, TransformationMatrix, ) from amulet_map_editor.api.opengl.resource_pack import ( OpenGLResourcePackManager, OpenGLResourcePack, ) from amulet_map_editor.api.opengl import Drawable, ThreadedObject, ContextManager if TYPE_CHECKING: from amulet.api.level import BaseLevel log = logging.getLogger(__name__) class RenderLevel(OpenGLResourcePackManager, Drawable, ThreadedObject, ContextManager): """A RenderLevel holds a reference to a level and manages all the geometry and drawing for that level.""" def __init__( self, context_identifier: Any, opengl_resource_pack: OpenGLResourcePack, level: "BaseLevel", draw_box=False, draw_floor=False, draw_ceil=False, limit_bounds=False, ): """ Create a new RenderLevel instance. :param context_identifier: The identifier for the opengl context. :param opengl_resource_pack: The resource pack to use for models and textures. :param level: The level to pull data from. :param draw_box: Should the box around the level be drawn. :param draw_floor: Should the floor below the level be drawn. :param draw_ceil: Should the ceiling above the level be drawn. :param limit_bounds: Should the chunks be limited to the bounds of the level. """ OpenGLResourcePackManager.__init__(self, opengl_resource_pack) ContextManager.__init__(self, context_identifier) self._level = level self._camera_location: CameraLocationType = (0, 150, 0) # yaw (-180 to 180), pitch (-90 to 90) self._camera_rotation: CameraRotationType = (0, 90) self._dimension: Dimension = level.dimensions[0] self._render_distance = 5 self._garbage_distance = 10 self._draw_box = draw_box self._draw_floor = draw_floor self._draw_ceil = draw_ceil self._limit_bounds = limit_bounds self._selection = None self._chunk_manager = ChunkManager(self.context_identifier, self.resource_pack) self._last_rebuild_camera_location: Optional[numpy.ndarray] = ( None # x, z camera location ) self._needs_rebuild = ( True # Should we go back to the beginning and re-find chunks to rebuild ) self._chunk_rebuilds = self._rebuild_generator() self._rebuild_time = 0 @property def level(self) -> "BaseLevel": return self._level @property def chunk_manager(self) -> ChunkManager: return self._chunk_manager def is_closeable(self): return True def _rebuild_generator(self) -> Generator[Optional[ChunkCoordinates], None, None]: """A generator of chunk coordinates to rebuild. This is an infinite length generator.""" while True: if self._needs_rebuild: self._needs_rebuild = False # a set of chunks that are next to chunks that have changed but have not changed themselves chunk_rebuilt = set() chunk_not_loaded = [] # a list of chunks that have not been loaded for chunk_coords in self.chunk_coords(): # for all chunks within radius of the player if self.chunk_manager.render_chunk_needs_rebuild(chunk_coords): # if the render chunk exists and the state has changed # rebuild that chunk chunk_rebuilt.add(chunk_coords) yield chunk_coords for offset in [(-1, 0), (1, 0), (0, -1), (0, 1)]: # for all surrounding chunks chunk_coords_ = ( chunk_coords[0] + offset[0], chunk_coords[1] + offset[1], ) if ( chunk_coords_ not in chunk_rebuilt and chunk_coords in self.chunk_manager and not self.chunk_manager.render_chunk_needs_rebuild( chunk_coords_ ) ): # if the chunk has not already been rebuilt and it exists # yield it to be rebuilt yield chunk_coords_ # store the coords so that it does not get rebuilt twice chunk_rebuilt.add( chunk_coords_ ) # so that it doesn't get picked up again # if the rebuild flag has been set go to the beginning if self._needs_rebuild: break elif chunk_coords not in self.chunk_manager: # if the chunk is not yet loaded, mark it for loading. chunk_not_loaded.append(chunk_coords) # if the rebuild flag has been set go to the beginning if self._needs_rebuild: continue for chunk_coords in chunk_not_loaded: # if the rebuild flag has been set go to the beginning if self._needs_rebuild: break yield chunk_coords else: yield None def thread_action(self): # first check if there is a chunk that exists and needs rebuilding camera = numpy.asarray(self.camera_location)[[0, 2]] if self._last_rebuild_camera_location is None or numpy.sum( (self._last_rebuild_camera_location - camera) ** 2 ) > min(2048, self.render_distance * 16 - 8): # if the camera has moved more than 32 blocks set the rebuild flag self._needs_rebuild = True self._last_rebuild_camera_location = camera chunk_coords = next(self._chunk_rebuilds) if chunk_coords is not None: # generate the chunk chunk = RenderChunk( self.context_identifier, self.resource_pack, self.level, self.chunk_manager.region_size, chunk_coords, self.dimension, draw_floor=self.draw_floor, draw_ceil=self.draw_ceil, limit_bounds=self._limit_bounds, ) try: chunk.create_geometry() except: log.error( f"Failed generating chunk geometry for chunk {chunk_coords}", exc_info=True, ) self.chunk_manager.add_render_chunk(chunk) t = time.time() if t > self._rebuild_time + 1: self._rebuild_time = t self.chunk_manager.rebuild() def enable(self): """Enable chunk generation in a new thread.""" self._needs_rebuild = True def unload(self): """Unload all loaded data. Can be resumed by calling enable.""" self.run_garbage_collector(True) def close(self): self.unload() @property def camera_location(self) -> CameraLocationType: """The x, y, z coordinates of the camera.""" return self._camera_location @camera_location.setter def camera_location(self, value: CameraLocationType): self._camera_location = value @property def camera_rotation(self) -> CameraRotationType: """The rotation of the camera. (yaw, pitch). This should behave the same as how Minecraft handles it. """ return self._camera_rotation @camera_rotation.setter def camera_rotation(self, value: CameraRotationType): """Set the rotation of the camera. (yaw, pitch). This should behave the same as how Minecraft handles it. """ self._camera_rotation = value @property def dimension(self) -> Dimension: """The dimension currently being displayed.""" return self._dimension @dimension.setter def dimension(self, dimension: Dimension): self._dimension = dimension self.run_garbage_collector(True) self._needs_rebuild = True @property def render_distance(self) -> int: """The radius around the camera within which to load chunks.""" return self._render_distance @render_distance.setter def render_distance(self, val: int): assert isinstance(val, int), "Render distance must be an int" self._render_distance = val self._garbage_distance = val + 5 self._needs_rebuild = True @property def draw_box(self): """Should the selection box around the level be drawn.""" return self._draw_box @property def draw_floor(self): """Should the floor under the level be drawn.""" return self._draw_floor @property def draw_ceil(self): """Should the ceiling above the level be drawn.""" return self._draw_ceil def chunk_coords(self) -> Generator[ChunkCoordinates, None, None]: """Get all of the chunks to draw/load""" # This yield chunk coordinates in a spiral around the camera # TODO: Perhaps redesign this to prioritise chunks in front of the camera cx, cz = int(self.camera_location[0]) >> 4, int(self.camera_location[2]) >> 4 sign = 1 length = 1 for _ in range(self.render_distance * 2 + 1): for _ in range(length): yield cx, cz cx += sign for _ in range(length): yield cx, cz cz += sign sign *= -1 length += 1 def draw(self, camera_matrix: TransformationMatrix): self._chunk_manager.draw(camera_matrix, self.camera_location) if self._draw_box: if self._selection is None: self._selection = GreenRenderSelectionGroup( self.context_identifier, self.resource_pack, self.level.bounds(self.dimension), ) self._selection.draw( camera_matrix, self.camera_location, ) def run_garbage_collector(self, remove_all=False): if remove_all: self._chunk_manager.unload() self._level.unload() else: safe_area = ( self._dimension, int(self.camera_location[0] // 16 - self._garbage_distance), int(self.camera_location[2] // 16 - self._garbage_distance), int(self.camera_location[0] // 16 + self._garbage_distance), int(self.camera_location[2] // 16 + self._garbage_distance), ) self._chunk_manager.unload(safe_area[1:]) self._level.unload(safe_area) def _rebuild(self): """Unload all the chunks so they can be rebuilt.""" self._chunk_manager.unload() self._needs_rebuild = True def rebuild_changed(self): """Rebuild the chunks that have changed.""" self._needs_rebuild = True
Amulet-Map-Editor
amulet_map_editor\api\opengl\mesh\level\region.py
from OpenGL.GL import ( GL_DYNAMIC_DRAW, glBindVertexArray, glBindBuffer, GL_ARRAY_BUFFER, glBufferSubData, ) from typing import Dict, Tuple, Optional import numpy import queue from .chunk import RenderChunk from amulet_map_editor.api.opengl.mesh.tri_mesh import TriMesh from amulet_map_editor.api.opengl.resource_pack import OpenGLResourcePack from amulet_map_editor.api.opengl.matrix import displacement_matrix from amulet_map_editor.api.opengl.data_types import TransformationMatrix class ChunkManager: def __init__( self, context_identifier: str, resource_pack: OpenGLResourcePack, region_size=16 ): self.context_identifier = context_identifier self._resource_pack = resource_pack self.region_size = region_size self._regions: Dict[Tuple[int, int], RenderRegion] = {} # added chunks are put in here and then processed on the next call of draw # This is because add_render_chunk can be called from a different thread to draw # which causes issues due to dictionaries resizing self._chunk_temp: queue.Queue = queue.Queue() self._chunk_temp_set = set() self._rebuild_regions = [] def add_render_chunk(self, render_chunk: RenderChunk): """Add a RenderChunk to the database. A call to _merge_chunk_temp from the main thread will be needed for them to be drawn. This is done after the next draw call.""" self._chunk_temp.put(render_chunk) chunk_coords = (render_chunk.cx, render_chunk.cz) self._chunk_temp_set.add(chunk_coords) def render_chunk_needs_rebuild(self, chunk_coords: Tuple[int, int]) -> bool: return ( chunk_coords not in self._chunk_temp_set and self.render_chunk_in_main_database(chunk_coords) and self.get_render_chunk(chunk_coords).needs_rebuild() ) def get_render_chunk(self, chunk_coords: Tuple[int, int]) -> RenderChunk: """Get a RenderChunk from the database. Might throw a key error if it has not been added to the real database yet.""" return self._regions[self.region_coords(*chunk_coords)].get_render_chunk( chunk_coords ) def _merge_chunk_temp(self): for _ in range(self._chunk_temp.qsize()): render_chunk = self._chunk_temp.get() region_coords = self.region_coords(render_chunk.cx, render_chunk.cz) if region_coords not in self._regions: self._regions[region_coords] = RenderRegion( region_coords[0], region_coords[1], self.region_size, self.context_identifier, self._resource_pack, ) self._regions[region_coords].add_render_chunk(render_chunk) self._chunk_temp_set.clear() def __contains__(self, chunk_coords: Tuple[int, int]): return ( chunk_coords in self._chunk_temp_set or self.render_chunk_in_main_database(chunk_coords) ) def render_chunk_in_main_database(self, chunk_coords: Tuple[int, int]) -> bool: region_coords = self.region_coords(*chunk_coords) return ( region_coords in self._regions and chunk_coords in self._regions[region_coords] ) def region_coords(self, cx, cz): return cx // self.region_size, cz // self.region_size def draw(self, camera_matrix: TransformationMatrix, camera): cam_rx, cam_rz = numpy.floor( numpy.array(camera)[[0, 2]] / (16 * self.region_size) ) cam_cx, cam_cz = numpy.floor(numpy.array(camera)[[0, 2]] / 16) for region in sorted( self._regions.values(), key=lambda x: abs(x.rx - cam_rx) + abs(x.rz - cam_rz), reverse=True, ): region.draw(camera_matrix, cam_cx, cam_cz) self._merge_chunk_temp() def unload(self, safe_area: Tuple[int, int, int, int] = None): if safe_area is None: for _ in range(self._chunk_temp.qsize()): self._chunk_temp.get() self._chunk_temp_set.clear() for region in self._regions.values(): region.unload() self._regions.clear() else: min_rx, min_rz = self.region_coords(*safe_area[:2]) max_rx, max_rz = self.region_coords(*safe_area[2:]) delete_regions = [] for region in self._regions.values(): if not ( min_rx <= region.rx <= max_rx and min_rz <= region.rz <= max_rz ): region.unload() delete_regions.append((region.rx, region.rz)) for region in delete_regions: del self._regions[region] def rebuild(self): """Rebuild a single region which was last rebuild the longest ago. Put this on a semi-fast clock to rebuild all regions.""" if not self._rebuild_regions: self._rebuild_regions = list(self._regions.keys()) if self._rebuild_regions: region = self._rebuild_regions.pop(0) if region in self._regions: self._regions[region].rebuild() MergedChunkLocationsType = Dict[Tuple[int, int], Tuple[int, int, int, int]] class RenderRegion(TriMesh): _merged_chunk_locations: MergedChunkLocationsType _temp_data: Optional[Tuple[numpy.ndarray, MergedChunkLocationsType]] def __init__( self, rx: int, rz: int, region_size: int, context_identifier: str, resource_pack: OpenGLResourcePack, ): """A group of RenderChunks to minimise the number of draw calls""" super().__init__(context_identifier, resource_pack) self.rx = rx self.rz = rz self._chunks: Dict[Tuple[int, int], RenderChunk] = {} self._merged_chunk_locations: MergedChunkLocationsType = {} self._manual_chunks: Dict[Tuple[int, int], RenderChunk] = {} # Merging is done on a new thread which can't modify the opengl state. # This stores the created data and the main thread loads it when drawing. self._temp_data = None self.region_transform = displacement_matrix( rx * region_size * 16, 0, rz * region_size * 16 ) @property def vertex_usage(self): return GL_DYNAMIC_DRAW def __repr__(self): return f"RenderRegion({self.rx}, {self.rz})" def __contains__(self, item): return item in self._chunks def add_render_chunk(self, render_chunk: RenderChunk): """Add a chunk to the region""" chunk_coords = (render_chunk.cx, render_chunk.cz) if chunk_coords in self._chunks: self._chunks[chunk_coords].unload() self._disable_merged_chunk(chunk_coords) self._chunks[chunk_coords] = render_chunk self._manual_chunks[chunk_coords] = render_chunk def get_render_chunk(self, chunk_coords: Tuple[int, int]): return self._chunks[chunk_coords] def _disable_merged_chunk(self, chunk_coords: Tuple[int, int]): """Zero out the region of memory in the merged chunks related to a given chunk""" if chunk_coords in self._merged_chunk_locations: ( offset, size, translucent_offset, translucent_size, ) = self._merged_chunk_locations.pop(chunk_coords) glBindVertexArray(self._vao) glBindBuffer(GL_ARRAY_BUFFER, self._vbo) glBufferSubData( GL_ARRAY_BUFFER, offset * 4, size * 4, numpy.zeros(size, dtype=numpy.float32), ) glBufferSubData( GL_ARRAY_BUFFER, translucent_offset * 4, translucent_size * 4, numpy.zeros(translucent_size, dtype=numpy.float32), ) glBindVertexArray(0) glBindBuffer(GL_ARRAY_BUFFER, 0) def rebuild(self): """Merges chunk geometry for the region into one large array. As each chunk is added it is drawn individually. After not too long the individual draw calls for each chunk will reach the bottleneck for python. To solve this we take the geometry for each chunk and merge them into one large array that only requires one draw call. :return: """ if self._manual_chunks: region_verts = [] region_verts_translucent = [] merged_locations: MergedChunkLocationsType = {} offset = 0 translucent_offset = 0 for chunk_location, chunk in self._chunks.items(): region_verts.append(chunk.verts[: chunk.verts_translucent]) region_verts_translucent.append(chunk.verts[chunk.verts_translucent :]) merged_locations[chunk_location] = [ offset, chunk.verts_translucent, translucent_offset, chunk.verts.size - chunk.verts_translucent, ] offset += chunk.verts_translucent translucent_offset += chunk.verts.size - chunk.verts_translucent for val in merged_locations.values(): val[2] += offset region_verts += region_verts_translucent if region_verts: verts = numpy.concatenate(region_verts) else: verts = self.new_empty_verts() self._temp_data = verts, merged_locations def _create_geometry(self): """Load the temporary vertex data into opengl.""" if self._temp_data is not None: self._setup() verts, merged_locations = self._temp_data self._temp_data = None self.draw_count = int(verts.size // self._vert_len) self._merged_chunk_locations = merged_locations self.change_verts(verts) for coord in merged_locations: chunk = self._manual_chunks.pop(coord, None) if chunk is not None: chunk.unload() def unload(self): """Unload all opengl data""" super().unload() for chunk in self._chunks.values(): chunk.unload() self._chunks.clear() def draw(self, camera_matrix: TransformationMatrix, cam_cx, cam_cz): self._create_geometry() transformation_matrix = numpy.matmul(camera_matrix, self.region_transform) super().draw(transformation_matrix) for chunk in sorted( self._manual_chunks.values(), key=lambda x: abs(x.cx - cam_cx) + abs(x.cz - cam_cz), reverse=True, ): chunk.draw(transformation_matrix)
Amulet-Map-Editor
amulet_map_editor\api\opengl\mesh\level\selection.py
from typing import Tuple from amulet_map_editor.api.opengl.mesh.selection import ( RenderSelection, RenderSelectionGroup, ) class GreenRenderSelection(RenderSelection): @property def box_tint(self) -> Tuple[float, float, float]: return 0.7, 1.0, 0.7 class GreenRenderSelectionGroup(RenderSelectionGroup): def _new_render_selection(self): return GreenRenderSelection(self._context_identifier, self.resource_pack)
Amulet-Map-Editor
amulet_map_editor\api\opengl\mesh\level\__init__.py
from .level import RenderLevel
Amulet-Map-Editor
amulet_map_editor\api\opengl\mesh\selection\__init__.py
from .box import RenderSelection, RenderSelectionEditable, RenderSelectionHighlightable from .group import RenderSelectionGroup, RenderSelectionGroupHighlightable
Amulet-Map-Editor
amulet_map_editor\api\opengl\mesh\level\chunk\chunk.py
import numpy from typing import TYPE_CHECKING, Tuple, List, Union import weakref import itertools import logging from amulet.api.errors import ChunkLoadError, ChunkDoesNotExist from amulet.api.chunk.blocks import Blocks from amulet.api.data_types import Dimension from amulet.api.level import BaseLevel from amulet.api.selection import SelectionBox from .chunk_builder import RenderChunkBuilder from amulet_map_editor.api.opengl.resource_pack import OpenGLResourcePack if TYPE_CHECKING: from amulet.api.chunk import Chunk log = logging.getLogger(__name__) class RenderChunk(RenderChunkBuilder): def __init__( self, context_identifier: str, resource_pack: OpenGLResourcePack, level: BaseLevel, region_size: int, chunk_coords: Tuple[int, int], dimension: Dimension, draw_floor: bool = False, draw_ceil: bool = False, limit_bounds: bool = False, ): # the chunk geometry is stored in chunk space (floating point) # at shader time it is transformed by the players transform super().__init__(context_identifier, resource_pack) self._level_ = weakref.ref(level) self._region_size = region_size self._coords = chunk_coords self._dimension = dimension self._draw_floor = draw_floor self._draw_ceil = draw_ceil self._limit_bounds = limit_bounds self._chunk_state = 0 # 0 = chunk does not exist, 1 = chunk exists but failed to load, 2 = chunk exists self._changed_time = 0 self._needs_rebuild = True self.verts_translucent = ( 0 # the offset into the above from which the faces can be translucent ) # self.chunk_lod1: numpy.ndarray = self.new_empty_verts() def __repr__(self): return f"RenderChunk({self._coords[0]}, {self._coords[1]})" def _setup(self): """Set up the opengl data which cannot be set up in another thread""" super()._setup() if self._needs_rebuild: self.change_verts() self._needs_rebuild = False @property def _level(self) -> BaseLevel: return self._level_() @property def offset(self) -> numpy.ndarray: return 16 * ( numpy.array([self._coords[0], 0, self._coords[1]]) % self._region_size ) @property def dimension(self) -> str: return self._dimension @property def cx(self) -> int: return self._coords[0] @property def cz(self) -> int: return self._coords[1] @property def coords(self) -> Tuple[int, int]: return self._coords @property def chunk(self) -> "Chunk": return self._level.get_chunk(self.cx, self.cz, self._dimension) @property def chunk_state(self) -> int: return self._chunk_state def needs_rebuild(self): """has the chunk data changed since the last rebuild""" try: chunk = self.chunk except ChunkDoesNotExist: chunk_state = 0 except ChunkLoadError: chunk_state = 1 else: chunk_state = 2 if chunk.changed_time != self._changed_time: return True return chunk_state != self._chunk_state def _sub_chunks(self, blocks: Blocks) -> List[Tuple[numpy.ndarray, int]]: """Create sub-chunk arrays that extend into the neighbour sub-chunks by one block. :param blocks: The Blocks array for the chunk. :return: A list of tuples containing the larger block array and the location of the sub-chunk """ sub_chunks = [] neighbour_chunks = {} for dx, dz in ((-1, 0), (1, 0), (0, -1), (0, 1)): try: neighbour_chunks[(dx, dz)] = self._level.get_chunk( self.cx + dx, self.cz + dz, self.dimension ).blocks except ChunkLoadError: continue for cy in blocks.sub_chunks: sub_chunk = blocks.get_sub_chunk(cy) larger_blocks = numpy.zeros( sub_chunk.shape + numpy.array((2, 2, 2)), sub_chunk.dtype ) sub_chunk_box = SelectionBox.create_sub_chunk_box(self.cx, cy, self.cz) if self._limit_bounds: if self._level.bounds(self.dimension).intersects(sub_chunk_box): boxes = self._level.bounds(self.dimension).intersection( sub_chunk_box ) for box in boxes.selection_boxes: larger_blocks[1:-1, 1:-1, 1:-1][ box.sub_chunk_slice(self.cx, cy, self.cz) ] = sub_chunk[box.sub_chunk_slice(self.cx, cy, self.cz)] else: continue else: larger_blocks[1:-1, 1:-1, 1:-1] = sub_chunk for chunk_offset, neighbour_blocks in neighbour_chunks.items(): if cy not in neighbour_blocks: continue if chunk_offset == (-1, 0): larger_blocks[0, 1:-1, 1:-1] = neighbour_blocks.get_sub_chunk(cy)[ -1, :, : ] elif chunk_offset == (1, 0): larger_blocks[-1, 1:-1, 1:-1] = neighbour_blocks.get_sub_chunk(cy)[ 0, :, : ] elif chunk_offset == (0, -1): larger_blocks[1:-1, 1:-1, 0] = neighbour_blocks.get_sub_chunk(cy)[ :, :, -1 ] elif chunk_offset == (0, 1): larger_blocks[1:-1, 1:-1, -1] = neighbour_blocks.get_sub_chunk(cy)[ :, :, 0 ] if cy - 1 in blocks: larger_blocks[1:-1, 0, 1:-1] = blocks.get_sub_chunk(cy - 1)[:, -1, :] if cy + 1 in blocks: larger_blocks[1:-1, -1, 1:-1] = blocks.get_sub_chunk(cy + 1)[:, 0, :] sub_chunks.append((larger_blocks, cy * 16)) return sub_chunks def create_geometry(self): try: chunk = self.chunk except ChunkDoesNotExist: self._create_empty_geometry() self._chunk_state = 0 except ChunkLoadError: log.info(f"Error loading chunk {self.coords}", exc_info=True) self._create_error_geometry() self._chunk_state = 1 else: self._changed_time = chunk.changed_time self._chunk_state = 2 chunk_verts, chunk_verts_translucent = self._create_lod0_multi( self._sub_chunks(chunk.blocks) ) self._set_verts(chunk_verts, chunk_verts_translucent) if self._draw_floor or self._draw_ceil: plane = self._create_grid( "amulet", "amulet_ui/translucent_white", (0.55, 0.5, 0.9) if (self.cx + self.cz) % 2 else (0.4, 0.4, 0.85), ) self.verts = numpy.concatenate([self.verts, plane.ravel()], 0) self.draw_count += len(plane) self._needs_rebuild = True def _create_empty_geometry(self): if self._draw_floor: plane = self._create_grid( "amulet", "amulet_ui/translucent_white", (0.3, 0.3, 0.3) if (self.cx + self.cz) % 2 else (0.2, 0.2, 0.2), ) self.verts = plane.ravel() self.draw_count = len(plane) else: self.verts = numpy.ones(0, numpy.float32) self.draw_count = 0 def _create_grid( self, texture_namespace: str, texture_path: str, tint: Tuple[float, float, float], ): plane: numpy.ndarray = numpy.ones( (self._vert_len * 12 * (self._draw_floor + self._draw_ceil)), dtype=numpy.float32, ).reshape((-1, self._vert_len)) bounds = self._level.bounds(self.dimension) if self._draw_floor: plane[:12, :3], plane[:12, 3:5] = self._create_chunk_plane( bounds.min_y - 0.01 ) if self._draw_ceil: plane[12:, :3], plane[12:, 3:5] = self._create_chunk_plane( bounds.max_y + 0.01 ) elif self._draw_ceil: plane[:12, :3], plane[:12, 3:5] = self._create_chunk_plane( bounds.max_y + 0.01 ) plane[:, 5:9] = self.resource_pack.texture_bounds( self.resource_pack.get_texture_path(texture_namespace, texture_path) ) plane[:, 9:12] = tint return plane def _create_chunk_plane( self, height: Union[int, float] ) -> Tuple[numpy.ndarray, numpy.ndarray]: box = numpy.array([(0, height, 0), (16, height, 16)]) + self.offset _box_coordinates = numpy.array(list(itertools.product(*box.T.tolist()))) _cube_face_lut = numpy.array( [ # This maps to the verticies used (defined in cube_vert_lut) 0, 4, 5, 1, 3, 7, 6, 2, ] ) box = box.ravel() _texture_index = numpy.array([0, 2, 3, 5, 0, 2, 3, 5], numpy.uint32) _uv_slice = numpy.array( [0, 1, 2, 1, 2, 3, 0, 3] * 2, dtype=numpy.uint32 ).reshape((-1, 8)) + numpy.arange(0, 8, 4).reshape((-1, 1)) _tri_face = numpy.array([0, 1, 2, 0, 2, 3] * 2, numpy.uint32).reshape( (-1, 6) ) + numpy.arange(0, 8, 4).reshape((-1, 1)) return ( _box_coordinates[_cube_face_lut[_tri_face]].reshape((-1, 3)), box[_texture_index[_uv_slice]] .reshape(-1, 2)[_tri_face, :] .reshape((-1, 2)), ) def _create_error_geometry(self): if self._draw_floor: plane = self._create_grid( "amulet", "amulet_ui/translucent_white", (1, 0.2, 0.2) if (self.cx + self.cz) % 2 else (0.75, 0.2, 0.2), ) self.verts = plane.ravel() self.draw_count = len(plane) else: self.verts = numpy.ones(0, numpy.float32) self.draw_count = 0 def _create_lod1( self, blocks: numpy.ndarray, larger_blocks: numpy.ndarray, unique_blocks: numpy.ndarray, ): # TODO self.verts: numpy.ndarray = self.new_empty_verts() # self.chunk_lod1: numpy.ndarray = self.new_empty_verts()
Amulet-Map-Editor
amulet_map_editor\api\opengl\mesh\level\chunk\chunk_builder.py
import numpy from typing import Tuple, List from amulet.api.chunk import Chunk from amulet_map_editor.api.opengl.mesh import TriMesh from amulet_map_editor.api.opengl.resource_pack import ( OpenGLResourcePackManagerStatic, OpenGLResourcePack, ) try: from .chunk_builder_cy import create_lod0_chunk except: raise Exception( "Could not import cython chunk mesher. The cython code must be compiled first." ) class RenderChunkBuilder(TriMesh): """A class to define the logic to generate geometry from a block array""" def __init__(self, context_identifier: str, resource_pack: OpenGLResourcePack): TriMesh.__init__(self, context_identifier, resource_pack) @property def chunk(self) -> Chunk: raise NotImplementedError @property def offset(self) -> numpy.ndarray: raise NotImplementedError @staticmethod def _get_block_data(blocks: numpy.ndarray) -> Tuple[numpy.ndarray, numpy.ndarray]: """Given a Chunk object will return the chunk arrays needed to generate geometry :returns: block array of the chunk, block array one block larger than the chunk, array of unique blocks """ larger_blocks = numpy.zeros(blocks.shape + numpy.array((2, 2, 2)), blocks.dtype) larger_blocks[1:-1, 1:-1, 1:-1] = blocks unique_blocks = numpy.unique(larger_blocks) return larger_blocks, unique_blocks def create_geometry(self): raise NotImplementedError def _set_verts( self, chunk_verts: List[numpy.ndarray], chunk_verts_translucent: List[numpy.ndarray], ): if chunk_verts: self.verts = numpy.concatenate(chunk_verts, None) self.verts_translucent = self.verts.size else: self.verts = self.new_empty_verts() if chunk_verts_translucent: chunk_verts_translucent.insert(0, self.verts) self.verts = numpy.concatenate(chunk_verts_translucent, None) self.draw_count = int(self.verts.size // self._vert_len) def _create_lod0_multi( self, blocks: List[Tuple[numpy.ndarray, int]] ) -> Tuple[List[numpy.ndarray], List[numpy.ndarray]]: """Create LOD0 geometry data for every sub-chunk in a given chunk. :param blocks: A list of tuples containing block arrays extending one block outside the sub-chunk in each direction. :return: Opaque block vertices, translucent block vertices. """ return create_lod0_chunk( self.resource_pack, self.offset, blocks, self.chunk.block_palette, self._vert_len, )
Amulet-Map-Editor
amulet_map_editor\api\opengl\mesh\level\chunk\__init__.py
from .chunk import RenderChunk
Amulet-Map-Editor
amulet_map_editor\api\opengl\mesh\selection\box\colours.json
{ "box_normal": [1.0, 1.0, 1.0], "box_highlight": [0.5, 0.5, 1.0], "box_highlight_move": [1.0, 0.7, 0.3], "box_edge": [0.5, 1.0, 1.0], "box_corner": [1.0, 1.0, 0.5], "box_point1": [0.0, 1.0, 0.0], "box_point2": [0.0, 0.0, 1.0] }
Amulet-Map-Editor
amulet_map_editor\api\opengl\mesh\selection\box\colours.py
import os import json colours_path = os.path.join(os.path.dirname(__file__), "colours.json") if os.path.isfile(colours_path): with open(colours_path) as f: colours = json.load(f) if isinstance(colours, dict): colours = { key: tuple(float(c) for c in val) for key, val in colours.items() if isinstance(val, list) and all(isinstance(c, (float, int)) for c in val) } else: colours = {} else: colours = {}
Amulet-Map-Editor
amulet_map_editor\api\opengl\mesh\selection\box\render_selection.py
import numpy from OpenGL.GL import ( GL_TRIANGLES, GL_DYNAMIC_DRAW, glCullFace, GL_FRONT, GL_BACK, glDisable, glEnable, GL_DEPTH_TEST, GL_LINE_STRIP, glGetBooleanv, glGetIntegerv, GL_CULL_FACE_MODE, ) import itertools from typing import Tuple, Optional, Union from amulet.api.selection import SelectionBox, SelectionGroup from amulet_map_editor.api.opengl.mesh.tri_mesh import TriMesh from amulet_map_editor.api.opengl.resource_pack import ( OpenGLResourcePack, OpenGLResourcePackManagerStatic, ) from amulet.api.data_types import BlockCoordinatesAny, PointCoordinatesAny from amulet_map_editor.api.opengl.matrix import displacement_matrix from amulet_map_editor.api.opengl.data_types import RGBColour from .colours import colours class RenderSelection(TriMesh, OpenGLResourcePackManagerStatic): """A drawable selection box""" def __init__(self, context_identifier: str, resource_pack: OpenGLResourcePack): TriMesh.__init__(self, context_identifier, resource_pack) self._points: numpy.ndarray = numpy.zeros( (2, 3), dtype=numpy.int64 ) # The points set using point1 and point2 self._bounds: Optional[numpy.ndarray] = None # The min and max locations self.transformation_matrix = numpy.eye(4, dtype=numpy.float64) self._needs_rebuild = True self._volume = 1 self._init_verts() self.draw_count = 36 self._draw_mode = GL_TRIANGLES @property def box_tint(self) -> RGBColour: """The tint colour to apply to the white texture.""" return colours.get("box_normal", (1, 1, 1)) def _init_verts(self): """Initialise the vertex values""" self.verts = numpy.zeros((6 * 2 * 3, self._vert_len), dtype=numpy.float32) self.verts[:36, 5:9] = self.resource_pack.texture_bounds( self.resource_pack.get_texture_path("amulet", "amulet_ui/selection") ) self.verts[:, 9:12] = self.box_tint def __contains__( self, position: Union[BlockCoordinatesAny, PointCoordinatesAny] ) -> bool: """ Is the block position inside the selection box cuboid. :param position: (x, y, z) :return: True if the position is inside the box otherwise False """ point = numpy.array(position) return numpy.all(self.min <= point) and numpy.all(point < self.max) def _offset_points(self) -> numpy.ndarray: points = self._points.copy() points[0] -= self.point1 > self.point2 points[1] -= self.point1 <= self.point2 return points def _from_offset_points(self, offset_points: numpy.ndarray): points = offset_points.copy() points[0] += offset_points[0] > offset_points[1] points[1] += offset_points[0] <= offset_points[1] self._points[:] = points @property def vertex_usage(self): return GL_DYNAMIC_DRAW @property def draw_mode(self): return self._draw_mode def _mark_recreate(self): self._bounds = None self._needs_rebuild = True @property def points(self) -> numpy.ndarray: return self._points.copy() @points.setter def points(self, points: numpy.ndarray): if not isinstance(points, numpy.ndarray) and points.shape == (2, 3): raise TypeError("points must be a numpy array of size 2x3.") self.point1, self.point2 = points @property def point1(self) -> numpy.ndarray: return self.points[0] @point1.setter def point1(self, val: PointCoordinatesAny): if not numpy.array_equal(self._points[0], val): self._points[0] = numpy.floor(val) self._mark_recreate() @property def point2(self) -> numpy.ndarray: return self.points[1] @point2.setter def point2(self, val: PointCoordinatesAny): if not numpy.array_equal(self._points[1], val): self._points[1] = numpy.floor(val) self._mark_recreate() @property def bounds(self) -> numpy.ndarray: """The array storing min and max locations""" if self._bounds is None: self._bounds = numpy.sort(self._points, 0) return self._bounds @property def selection_box(self) -> SelectionBox: return SelectionBox(self.point1, self.point2) @selection_box.setter def selection_box(self, selection_box: SelectionBox): if not isinstance(selection_box, SelectionBox): raise TypeError("selection_box must be a SelectionBox.") self.point1 = selection_box.point_1 self.point2 = selection_box.point_2 @property def selection_group(self) -> SelectionGroup: return SelectionGroup(self.selection_box) @property def min(self) -> numpy.ndarray: return self.bounds[0] @property def max(self) -> numpy.ndarray: return self.bounds[1] def _create_box( self, box_min: PointCoordinatesAny, box_max: PointCoordinatesAny ) -> Tuple[numpy.ndarray, numpy.ndarray]: return self._create_box_faces( box_min, box_max, True, True, True, True, True, True ) @staticmethod def _create_box_faces( box_min: PointCoordinatesAny, box_max: PointCoordinatesAny, up: bool = False, down: bool = False, north: bool = False, south: bool = False, east: bool = False, west: bool = False, ) -> Tuple[numpy.ndarray, numpy.ndarray]: box = numpy.sort([box_min, box_max], 0) _face_count = sum([up, down, north, south, east, west]) if not _face_count: raise ValueError("At least one of the faces must be enabled.") _box_coordinates = numpy.array(list(itertools.product(*box.T.tolist()))) _cube_face_lut = numpy.array( [ # This maps to the vertices used (defined in cube_vert_lut) 0, 4, 5, 1, # down ] * down + [0, 1, 3, 2] * west # west + [4, 0, 2, 6] * north # north + [5, 4, 6, 7] * east # east + [1, 5, 7, 3] * south # south + [3, 7, 6, 2] * up # up ) box = box.ravel() _texture_index = numpy.array( [0, 2, 3, 5] * down # down + [2, 1, 5, 4] * west # west + [3, 1, 0, 4] * north # north + [5, 1, 2, 4] * east # east + [0, 1, 3, 4] * south # south + [0, 5, 3, 2] * up, # up numpy.uint32, ) _uv_slice = numpy.array( [0, 1, 2, 1, 2, 3, 0, 3] * _face_count, dtype=numpy.uint32 ).reshape((_face_count, 8)) + numpy.arange(0, _face_count * 4, 4).reshape( (_face_count, 1) ) _tri_face = numpy.array([0, 1, 2, 2, 3, 0] * _face_count, numpy.uint32).reshape( (_face_count, 6) ) + numpy.arange(0, _face_count * 4, 4).reshape((_face_count, 1)) return ( _box_coordinates[_cube_face_lut[_tri_face]].reshape((-1, 3)), box[_texture_index[_uv_slice]] .reshape(-1, 2)[_tri_face, :] .reshape((-1, 2)), ) def _create_geometry_(self): self.verts[:36, :3], self.verts[:36, 3:5] = self._create_box( self.min % 16 - 0.005, self.min % 16 + self.max - self.min + 0.005 ) self.verts[:36, 3:5] /= 16 def _create_geometry(self): self._setup() self._create_geometry_() self.transformation_matrix = displacement_matrix(*self.min - self.min % 16) self.change_verts() self._volume = numpy.product(self.max - self.min) self._needs_rebuild = False def draw( self, camera_matrix: numpy.ndarray, camera_position: PointCoordinatesAny = None ): """ Draw the selection box :param camera_matrix: 4x4 transformation matrix for the camera :param camera_position: The position of the camera. Used to flip draw direction if camera inside box. :return: """ self._setup() if self._needs_rebuild: self._create_geometry() self._draw_mode = GL_TRIANGLES transformation_matrix = numpy.matmul(camera_matrix, self.transformation_matrix) depth_state = glGetBooleanv(GL_DEPTH_TEST) cull_state = glGetIntegerv(GL_CULL_FACE_MODE) if camera_position is not None and camera_position in self: if cull_state == GL_BACK: glCullFace(GL_FRONT) elif cull_state == GL_FRONT: glCullFace(GL_BACK) self.draw_start = 0 self.draw_count = 36 super()._draw(transformation_matrix) # draw the lines around the boxes if depth_state: glDisable(GL_DEPTH_TEST) self._draw_mode = GL_LINE_STRIP super()._draw(transformation_matrix) if depth_state: glEnable(GL_DEPTH_TEST) glCullFace(cull_state)
Amulet-Map-Editor
amulet_map_editor\api\opengl\mesh\selection\box\render_selection_editable.py
import numpy from OpenGL.GL import ( GL_TRIANGLES, glCullFace, GL_FRONT, GL_BACK, glDisable, GL_DEPTH_TEST, GL_LINE_STRIP, glEnable, glGetBooleanv, glGetIntegerv, GL_CULL_FACE_MODE, ) from amulet.api.data_types import PointCoordinatesAny from .render_selection_highlightable import RenderSelectionHighlightable from amulet_map_editor.api.opengl.resource_pack import OpenGLResourcePack from amulet_map_editor.api.opengl.data_types import RGBColour from .colours import colours class RenderSelectionEditable(RenderSelectionHighlightable): """A drawable selection box with additional editing controls""" def __init__(self, context_identifier: str, resource_pack: OpenGLResourcePack): super().__init__(context_identifier, resource_pack) # is the locked or is it being modified. Changes the colour of the faces. self._locked = True def _init_verts(self): # the first 36 verts are used for the full box which is used for lines # the next 36 verts are used for the inset faces # the next 144 verts are used for the edges # the next 144 verts are used for the corners verts_per_quad = 2 * 3 # triangles * verts self.verts = numpy.zeros( ( 6 * verts_per_quad + 6 # original box verts (used for the lines) * 9 * verts_per_quad, # new verts self._vert_len, ), dtype=numpy.float32, ) self.verts[:, 5:9] = self.resource_pack.texture_bounds( self.resource_pack.get_texture_path("amulet", "amulet_ui/selection") ) self.verts[verts_per_quad * 6 :, 9:12] = self.box_tint self.verts[verts_per_quad * 12 : verts_per_quad * 36, 9:12] = self.edge_colour @property def highlight_colour(self) -> RGBColour: if self.locked: return colours.get("box_highlight", (0.5, 0.5, 1.0)) else: return colours.get("box_highlight_move", (1.0, 0.7, 0.3)) @property def edge_colour(self) -> RGBColour: return colours.get("box_edge", (0.5, 1.0, 1.0)) @property def corner_colour(self) -> RGBColour: return colours.get("box_corner", (1.0, 1.0, 0.5)) @property def point1_colour(self) -> RGBColour: return colours.get("box_point1", (0.0, 1.0, 0.0)) @property def point2_colour(self) -> RGBColour: return colours.get("box_point2", (0.0, 0.0, 1.0)) @property def locked(self) -> bool: """Is the selection locked or not. If locked (True) the highlight colour will be used, if unlocked (False) the moving colour will be used. """ return self._locked @locked.setter def locked(self, lock: bool): """Set if the selection locked or not. If locked (True) the highlight colour will be used, if unlocked (False) the moving colour will be used. """ self._locked = bool(lock) def _create_geometry_(self): super()._create_geometry_() point1, point2 = self._points - self.min + (self.min % 16) size = numpy.abs(point2 - point1) verts_per_face = 2 * 3 # triangles * verts # the edges of the box min_point, max_point = numpy.sort([point1, point2], 0).astype(numpy.float64) min_point -= 0.01 max_point += 0.01 # the edge points offset by the boundary amount. min_point_1 = min_point + numpy.min([numpy.ones(3), size / 4], 0) max_point_1 = max_point - numpy.min([numpy.ones(3), size / 4], 0) # down, up # west, east # north, south face_offset = verts_per_face * 6 # inset faces for axis in ("y", "z", "x"): ( self.verts[face_offset : face_offset + verts_per_face * 2, :3], self.verts[face_offset : face_offset + verts_per_face * 2, 3:5], ) = self._create_box_faces( ( min_point[0] if axis == "x" else min_point_1[0], min_point[1] if axis == "y" else min_point_1[1], min_point[2] if axis == "z" else min_point_1[2], ), ( max_point[0] if axis == "x" else max_point_1[0], max_point[1] if axis == "y" else max_point_1[1], max_point[2] if axis == "z" else max_point_1[2], ), up=axis == "y", down=axis == "y", north=axis == "z", south=axis == "z", west=axis == "x", east=axis == "x", ) face_offset += verts_per_face * 2 for y in (False, True): for x in (False, True): ( self.verts[face_offset : face_offset + verts_per_face * 2, :3], self.verts[face_offset : face_offset + verts_per_face * 2, 3:5], ) = self._create_box_faces( ( max_point_1[0] if x else min_point[0], max_point_1[1] if y else min_point[1], min_point_1[2], ), ( max_point[0] if x else min_point_1[0], max_point[1] if y else min_point_1[1], max_point_1[2], ), up=y, down=not y, west=not x, east=x, ) face_offset += verts_per_face * 2 for y in (False, True): for z in (False, True): ( self.verts[face_offset : face_offset + verts_per_face * 2, :3], self.verts[face_offset : face_offset + verts_per_face * 2, 3:5], ) = self._create_box_faces( ( min_point_1[0], max_point_1[1] if y else min_point[1], max_point_1[2] if z else min_point[2], ), ( max_point_1[0], max_point[1] if y else min_point_1[1], max_point[2] if z else min_point_1[2], ), up=y, down=not y, north=not z, south=z, ) face_offset += verts_per_face * 2 for x in (False, True): for z in (False, True): ( self.verts[face_offset : face_offset + verts_per_face * 2, :3], self.verts[face_offset : face_offset + verts_per_face * 2, 3:5], ) = self._create_box_faces( ( max_point_1[0] if x else min_point[0], min_point_1[1], max_point_1[2] if z else min_point[2], ), ( max_point[0] if x else min_point_1[0], max_point_1[1], max_point[2] if z else min_point_1[2], ), north=not z, south=z, west=not x, east=x, ) face_offset += verts_per_face * 2 self.verts[216:360, 9:12] = self.corner_colour corners = point2 >= point1 not_corners = numpy.invert(corners) # corners for y in (False, True): for z in (False, True): for x in (False, True): ( self.verts[face_offset : face_offset + verts_per_face * 3, :3], self.verts[face_offset : face_offset + verts_per_face * 3, 3:5], ) = self._create_box_faces( ( max_point_1[0] if x else min_point[0], max_point_1[1] if y else min_point[1], max_point_1[2] if z else min_point[2], ), ( max_point[0] if x else min_point_1[0], max_point[1] if y else min_point_1[1], max_point[2] if z else min_point_1[2], ), up=y, down=not y, north=not z, south=z, west=not x, east=x, ) if numpy.array_equal(corners, (x, y, z)): self.verts[ face_offset : face_offset + verts_per_face * 3, 9:12 ] = self.point2_colour elif numpy.array_equal(not_corners, (x, y, z)): self.verts[ face_offset : face_offset + verts_per_face * 3, 9:12 ] = self.point1_colour face_offset += verts_per_face * 3 self.verts[:, 3:5] /= 16 self.verts[36:72, 9:12] = self.box_tint indexes = numpy.zeros(6, numpy.uint8) if self.point2[0] > self.point1[0]: indexes[[4, 5]] = 0, 3 else: indexes[[4, 5]] = 3, 0 if self.point2[1] > self.point1[1]: indexes[[0, 1]] = 1, 4 else: indexes[[0, 1]] = 4, 1 if self.point2[2] > self.point1[2]: indexes[[2, 3]] = 2, 5 else: indexes[[2, 3]] = 5, 2 self.verts[36:72][ numpy.repeat(self._highlight_edges.ravel()[indexes], 6), 9:12 ] = self.highlight_colour def draw( self, camera_matrix: numpy.ndarray, camera_position: PointCoordinatesAny = None ): """ Draw the selection box :param camera_matrix: 4x4 transformation matrix for the camera :param camera_position: The position of the camera. Used to flip draw direction if camera inside box. :return: """ self._setup() if self._needs_rebuild: self._create_geometry() transformation_matrix = numpy.matmul(camera_matrix, self.transformation_matrix) depth_state = glGetBooleanv(GL_DEPTH_TEST) cull_state = glGetIntegerv(GL_CULL_FACE_MODE) # draw the lines around the boxes self.draw_start = 0 self.draw_count = 36 if depth_state: glDisable(GL_DEPTH_TEST) self._draw_mode = GL_LINE_STRIP super()._draw(transformation_matrix) if depth_state: glEnable(GL_DEPTH_TEST) if camera_position is not None: if camera_position in self: glCullFace(GL_FRONT) else: glCullFace(GL_BACK) self._draw_mode = GL_TRIANGLES self.draw_start = 36 # 6 faces, 9 quads/face, 2 triangles/quad, 3 verts/triangle self.draw_count = 324 super()._draw(transformation_matrix) glCullFace(cull_state)
Amulet-Map-Editor
amulet_map_editor\api\opengl\mesh\selection\box\render_selection_highlightable.py
from typing import Union import numpy from .render_selection import RenderSelection from amulet_map_editor.api.opengl.resource_pack import OpenGLResourcePack from amulet_map_editor.api.opengl.data_types import RGBColour from .colours import colours class RenderSelectionHighlightable(RenderSelection): """A drawable selection box with edges that can be highlighted""" def __init__(self, context_identifier: str, resource_pack: OpenGLResourcePack): super().__init__(context_identifier, resource_pack) # which edges are highlighted self._highlight_edges = numpy.zeros((2, 3), dtype=bool) @property def highlight_colour(self) -> RGBColour: return colours.get("box_highlight", (0.5, 0.5, 1.0)) def reset_highlight_edges(self): if numpy.any(self._highlight_edges): self.set_highlight_edges(False) def set_highlight_edges(self, highlight_edges: Union[numpy.ndarray, bool]): self._highlight_edges[:] = highlight_edges self._mark_recreate() def _create_geometry_(self): super()._create_geometry_() self.verts[:36, 9:12] = self.box_tint indexes = numpy.zeros(6, numpy.uint8) if self.point2[0] > self.point1[0]: indexes[[1, 3]] = 0, 3 else: indexes[[1, 3]] = 3, 0 if self.point2[1] > self.point1[1]: indexes[[0, 5]] = 1, 4 else: indexes[[0, 5]] = 4, 1 if self.point2[2] > self.point1[2]: indexes[[2, 4]] = 2, 5 else: indexes[[2, 4]] = 5, 2 # [1, 0, 2, 3, 5, 4] # 0 down 1 # 1 west 0 # 2 north 2 # 3 east 3 # 4 south 5 # 5 up 4 self.verts[:36][ numpy.repeat(self._highlight_edges.ravel()[indexes], 6), 9:12 ] = self.highlight_colour
Amulet-Map-Editor
amulet_map_editor\api\opengl\mesh\selection\box\__init__.py
from .render_selection import RenderSelection from .render_selection_editable import RenderSelectionEditable from .render_selection_highlightable import RenderSelectionHighlightable
Amulet-Map-Editor
amulet_map_editor\api\opengl\mesh\selection\group\render_selection_group.py
import numpy from typing import List from amulet_map_editor.api.opengl import Drawable, ContextManager from amulet_map_editor.api.opengl.resource_pack import ( OpenGLResourcePack, OpenGLResourcePackManagerStatic, ) from amulet.api.selection import SelectionGroup, SelectionBox from amulet.api.data_types import PointCoordinatesAny from amulet_map_editor.api.opengl.mesh.selection import RenderSelection class RenderSelectionGroup(Drawable, ContextManager, OpenGLResourcePackManagerStatic): """A group of selection boxes to be drawn""" def __init__( self, context_identifier: str, resource_pack: OpenGLResourcePack, selection: SelectionGroup = None, ): ContextManager.__init__(self, context_identifier) OpenGLResourcePackManagerStatic.__init__(self, resource_pack) self._boxes: List[RenderSelection] = [] if selection: self.selection_group = selection def __len__(self): return len(self._boxes) def __bool__(self): return bool(self._boxes) def _new_render_selection(self): return RenderSelection(self.context_identifier, self.resource_pack) @property def selection_group(self) -> SelectionGroup: return SelectionGroup( [SelectionBox(box.point1, box.point2) for box in self._boxes] ) @selection_group.setter def selection_group(self, selection_group: SelectionGroup): if not isinstance(selection_group, SelectionGroup): raise TypeError("selection_group must be a SelectionGroup.") self.unload() for box in selection_group.selection_boxes: render_box = self._new_render_selection() render_box.point1 = numpy.array(box.point_1) render_box.point2 = numpy.array(box.point_2) self._boxes.append(render_box) def draw( self, camera_matrix: numpy.ndarray, camera_position: PointCoordinatesAny = None ): for box in self._boxes: box.draw(camera_matrix, camera_position) def unload(self): while self._boxes: box = self._boxes.pop() box.unload()
Amulet-Map-Editor
amulet_map_editor\api\opengl\mesh\selection\group\render_selection_group_highlightable.py
from typing import List, Union import numpy from .render_selection_group import ( RenderSelectionGroup, ) from amulet_map_editor.api.opengl.mesh.selection import RenderSelectionHighlightable class RenderSelectionGroupHighlightable(RenderSelectionGroup): """A group of selection boxes to be drawn with an added editable box.""" def _new_render_selection(self): return RenderSelectionHighlightable( self._context_identifier, self.resource_pack ) def reset_highlight_edges(self): self._boxes: List[RenderSelectionHighlightable] for box in self._boxes: box.reset_highlight_edges() def set_highlight_edges( self, box_index: int, highlight_edges: Union[numpy.ndarray, bool] ): self._boxes: List[RenderSelectionHighlightable] self._boxes[box_index].set_highlight_edges(highlight_edges)
Amulet-Map-Editor
amulet_map_editor\api\opengl\mesh\selection\group\__init__.py
from .render_selection_group import RenderSelectionGroup from .render_selection_group_highlightable import RenderSelectionGroupHighlightable
Amulet-Map-Editor
amulet_map_editor\api\wx\ui\base_define.py
import wx import wx.lib.scrolledpanel from typing import Tuple, Type import PyMCTranslate from amulet.api.data_types import VersionNumberTuple, PlatformType from amulet_map_editor.api.wx.ui.base_select import EVT_ITEM_CHANGE, BaseSelect from amulet_map_editor.api.wx.ui.version_select import ( VersionSelect, EVT_VERSION_CHANGE, ) class BaseDefine(wx.Panel): def __init__( self, parent, translation_manager: PyMCTranslate.TranslationManager, select_type: Type[BaseSelect], orientation=wx.VERTICAL, platform: str = None, version_number: Tuple[int, int, int] = None, namespace: str = None, default_name: str = None, show_pick: bool = False, **kwargs, ): super().__init__(parent) self._translation_manager = translation_manager self._orientation = orientation self._sizer = wx.BoxSizer(orientation) left_sizer = wx.BoxSizer(wx.VERTICAL) if orientation == wx.HORIZONTAL: self._sizer.Add(left_sizer, 1, wx.EXPAND) else: self._sizer.Add(left_sizer, 2, wx.EXPAND) self._version_picker = VersionSelect( self, translation_manager, platform, version_number, **kwargs, ) left_sizer.Add(self._version_picker, 0, wx.EXPAND) self._version_picker.Bind(EVT_VERSION_CHANGE, self._on_version_change) self._picker = select_type( self, translation_manager, self._version_picker.platform, self._version_picker.version_number, self._version_picker.force_blockstate, namespace, default_name, show_pick, ) left_sizer.Add(self._picker, 1, wx.EXPAND | wx.TOP, 5) self._picker.Bind(EVT_ITEM_CHANGE, self._on_picker_change) self.SetSizerAndFit(self._sizer) self.Layout() def _on_picker_change(self, evt): raise NotImplementedError("This method should be overridden in child classes.") def _on_version_change(self, evt): self._picker.version = ( evt.platform, evt.version_number, evt.force_blockstate, ) evt.Skip() @property def platform(self) -> PlatformType: return self._version_picker.platform @platform.setter def platform(self, platform: PlatformType): self._version_picker.platform = platform @property def version_number(self) -> VersionNumberTuple: return self._version_picker.version_number @version_number.setter def version_number(self, version_number: VersionNumberTuple): self._version_picker.version_number = version_number @property def version(self) -> Tuple[PlatformType, VersionNumberTuple, bool]: return self._version_picker.version @version.setter def version(self, version: Tuple[PlatformType, VersionNumberTuple, bool]): self._version_picker.version = version @property def namespace(self) -> str: return self._picker.namespace @namespace.setter def namespace(self, namespace: str): self._picker.namespace = namespace
Amulet-Map-Editor
amulet_map_editor\api\wx\ui\base_select.py
import wx from wx.lib import newevent from typing import Tuple, List, Optional import PyMCTranslate from amulet_map_editor.api.image import COLOUR_PICKER ( ItemNamespaceChangeEvent, EVT_ITEM_NAMESPACE_CHANGE, ) = newevent.NewCommandEvent() # the namespace entry changed ( ItemNameChangeEvent, EVT_ITEM_NAME_CHANGE, ) = newevent.NewCommandEvent() # the name entry changed ( ItemChangeEvent, EVT_ITEM_CHANGE, ) = ( newevent.NewCommandEvent() ) # the name or namespace changed. Generated after EVT_ITEM_NAME_CHANGE ( PickEvent, EVT_PICK, ) = newevent.NewCommandEvent() # The pick button was pressed class BaseSelect(wx.Panel): TypeName = "?" def __init__( self, parent: wx.Window, translation_manager: PyMCTranslate.TranslationManager, platform: str, version_number: Tuple[int, int, int], force_blockstate: bool = None, namespace: str = None, default_name: str = None, show_pick: bool = False, ): super().__init__(parent, style=wx.BORDER_SIMPLE) self._sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self._sizer) self._translation_manager = translation_manager self._platform: Optional[str] = None self._version_number: Optional[Tuple[int, int, int]] = None self._force_blockstate: Optional[bool] = force_blockstate sizer = wx.BoxSizer(wx.HORIZONTAL) self._sizer.Add(sizer, 0, wx.EXPAND | wx.ALL, 5) text = wx.StaticText(self, label="Namespace:", style=wx.ALIGN_CENTER) sizer.Add(text, 1, wx.ALIGN_CENTER_VERTICAL) self._namespace_combo = wx.ComboBox(self) sizer.Add(self._namespace_combo, 2) self._set_version((platform, version_number, force_blockstate or False)) self._populate_namespace() self.set_namespace(namespace) self._namespace_combo.Bind( wx.EVT_TEXT, lambda evt: self._post_namespace_change() ) self._do_text_event = ( True # some widgets create events. This is used to suppress them ) self.Bind(EVT_ITEM_NAMESPACE_CHANGE, self._on_namespace_change) sizer = wx.BoxSizer(wx.VERTICAL) self._sizer.Add(sizer, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 5) header_sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(header_sizer, 0, wx.EXPAND | wx.BOTTOM, 5) header_sizer.Add( wx.StaticText( self, label=f"{self.TypeName.capitalize()} name:", style=wx.ALIGN_CENTER ), 1, wx.ALIGN_CENTER_VERTICAL, ) search_sizer = wx.BoxSizer(wx.HORIZONTAL) header_sizer.Add(search_sizer, 2, wx.EXPAND) self._search = wx.SearchCtrl(self) search_sizer.Add(self._search, 1, wx.ALIGN_CENTER_VERTICAL) self._search.Bind(wx.EVT_TEXT, self._on_search_change) if show_pick: pick_button = wx.BitmapButton(self, bitmap=COLOUR_PICKER.bitmap(22, 22)) search_sizer.Add(pick_button, 0, wx.LEFT | wx.ALIGN_CENTER_VERTICAL, 5) pick_button.Bind( wx.EVT_BUTTON, lambda evt: wx.PostEvent(self, PickEvent(self.GetId(), widget=self)), ) self._list_box = wx.ListBox(self, style=wx.LB_SINGLE) sizer.Add(self._list_box, 1, wx.EXPAND) self._names: List[str] = [] self._populate_item_name() self.set_name(default_name) self._list_box.Bind(wx.EVT_LISTBOX, lambda evt: self._post_item_change()) def _post_namespace_change(self): if self._do_text_event: wx.PostEvent( self, ItemNamespaceChangeEvent(self.GetId(), namespace=self.namespace) ) self._do_text_event = True def _post_item_change(self): wx.PostEvent(self, ItemNameChangeEvent(self.GetId(), name=self.name)), wx.PostEvent( self, ItemChangeEvent(self.GetId(), namespace=self.namespace, name=self.name), ) @property def version(self) -> Tuple[str, Tuple[int, int, int], bool]: return self._platform, self._version_number, self._force_blockstate @version.setter def version(self, version: Tuple[str, Tuple[int, int, int], bool]): self._set_version(version) self._populate_namespace() self.namespace = None def _set_version(self, version: Tuple[str, Tuple[int, int, int], bool]): assert ( version[0] in self._translation_manager.platforms() and version[1] in self._translation_manager.version_numbers(version[0]) and isinstance(version[2], bool) ), f"{version} is not a valid version" self._platform, self._version_number, self._force_blockstate = version @property def namespace(self) -> str: return self._namespace_combo.GetValue() @namespace.setter def namespace(self, namespace: str): self.set_namespace(namespace) wx.PostEvent( self, ItemNamespaceChangeEvent(self.GetId(), namespace=self.namespace) ) def set_namespace(self, namespace: str): namespace = namespace or "minecraft" if isinstance(namespace, str): if namespace in self._namespace_combo.GetItems(): self._namespace_combo.SetSelection( self._namespace_combo.GetItems().index(namespace) ) else: self._namespace_combo.ChangeValue(namespace) @property def name(self) -> str: name: str = self._list_box.GetString(self._list_box.GetSelection()) if self._list_box.GetSelection() == 0 and name.startswith('"'): name = name[1:-1] return name @name.setter def name(self, name: str): if self.set_name(name): self._post_item_change() def set_name(self, name: str) -> bool: name = name or "" self._search.ChangeValue(name) return self._update_item_name(name) def _populate_namespace(self): raise NotImplementedError("This method should be overridden in child classes.") def _populate_item_name(self): raise NotImplementedError("This method should be overridden in child classes.") def _on_namespace_change(self, evt): self._populate_item_name() self.name = None evt.Skip() def _on_search_change(self, evt): search_str = evt.GetString() if self._update_item_name(search_str): self._post_item_change() def _update_item_name(self, search_str: str) -> bool: names = [bn for bn in self._names if search_str in bn] if search_str not in names: names.insert(0, f'"{search_str}"') index = 0 selection = self._list_box.GetSelection() if selection != wx.NOT_FOUND: current_string = self._list_box.GetString(selection) if current_string in names: index = names.index(current_string) self._list_box.SetItems(names) if index: # if the previously selected string is in the list select that self._list_box.SetSelection(index) return False elif search_str in names: # if the searched text perfectly matches select that self._list_box.SetSelection(names.index(search_str)) return True elif len(self._list_box.GetItems()) >= 2: self._list_box.SetSelection(1) return True else: self._list_box.SetSelection(0) return True
Amulet-Map-Editor
amulet_map_editor\api\wx\ui\nbt_editor.py
from __future__ import annotations from functools import partial from collections.abc import MutableMapping, MutableSequence import wx from amulet_map_editor.api.wx.ui import simple import amulet_nbt as nbt from amulet_map_editor.api import image nbt_resources = image.nbt NBT_FILE = b"\x0a\x00\x0b\x68\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64\x08\x00\x04\x6e\x61\x6d\x65\x00\x09\x42\x61\x6e\x61\x6e\x72\x61\x6d\x61\x00" class NBTRadioButton(simple.SimplePanel): def __init__(self, parent, nbt_tag_class, icon): super(NBTRadioButton, self).__init__(parent, wx.HORIZONTAL) self.nbt_tag_class = nbt_tag_class self.radio_button = wx.RadioButton(self, wx.ID_ANY, wx.EmptyString) self.add_object(self.radio_button, 0, wx.ALIGN_CENTER | wx.ALL) self.tag_bitmap = wx.StaticBitmap(self, wx.ID_ANY, icon) self.tag_bitmap.SetToolTip(nbt_tag_class) self.add_object(self.tag_bitmap, 0, wx.ALIGN_CENTER | wx.ALL) def GetValue(self): return self.radio_button.GetValue() def SetValue(self, val): self.radio_button.SetValue(val) class NBTEditor(simple.SimplePanel): def __init__(self, parent, nbt_data, root_tag_name="", callback=None): super(NBTEditor, self).__init__(parent) self.nbt_data = nbt_data self.image_list = wx.ImageList(16, 16) self.image_map = { nbt.TAG_Byte: self.image_list.Add(nbt_resources.nbt_tag_byte.bitmap()), nbt.TAG_Short: self.image_list.Add(nbt_resources.nbt_tag_short.bitmap()), nbt.TAG_Int: self.image_list.Add(nbt_resources.nbt_tag_int.bitmap()), nbt.TAG_Long: self.image_list.Add(nbt_resources.nbt_tag_long.bitmap()), nbt.TAG_Float: self.image_list.Add(nbt_resources.nbt_tag_float.bitmap()), nbt.TAG_Double: self.image_list.Add(nbt_resources.nbt_tag_double.bitmap()), nbt.TAG_String: self.image_list.Add(nbt_resources.nbt_tag_string.bitmap()), nbt.TAG_Compound: self.image_list.Add( nbt_resources.nbt_tag_compound.bitmap() ), nbt.NamedTag: self.image_list.ImageCount - 1, nbt.TAG_List: self.image_list.Add(nbt_resources.nbt_tag_list.bitmap()), nbt.TAG_Byte_Array: self.image_list.Add( nbt_resources.nbt_tag_array.bitmap() ), nbt.TAG_Int_Array: self.image_list.ImageCount - 1, nbt.TAG_Long_Array: self.image_list.ImageCount - 1, } self.other = self.image_map[nbt.TAG_String] self.tree = self.build_tree(root_tag_name) self.add_object(self.tree, 1, wx.ALL | wx.CENTER | wx.EXPAND) button_row = simple.SimplePanel(self, wx.HORIZONTAL) self.commit_button = wx.Button(button_row, label="Commit") self.cancel_button = wx.Button(button_row, label="Cancel") button_row.add_object(self.commit_button, space=0) button_row.add_object(self.cancel_button, space=0) self.commit_button.Bind(wx.EVT_BUTTON, self.commit) self.cancel_button.Bind(wx.EVT_BUTTON, self._close) self.add_object(button_row, space=0) self.callback = callback def commit(self, evt): self.callback(self.nbt_data) evt.Skip() def _close(self, evt): self.Close(True) evt.Skip() def build_tree(self, root_tag_name=""): def add_tree_node(_tree: wx.TreeCtrl, _parent, _items): for key, value in _items.items(): new_child = None if isinstance(value, MutableMapping): new_child = _tree.AppendItem(_parent, key) add_tree_node(_tree, new_child, value) elif isinstance(value, MutableSequence): new_child = _tree.AppendItem(_parent, key) for i, item in enumerate(value): child_child = _tree.AppendItem(new_child, f"{item.value}") tree.SetItemData(child_child, (i, item)) tree.SetItemImage( child_child, self.image_map.get(item.__class__, self.other), wx.TreeItemIcon_Normal, ) else: new_child = _tree.AppendItem(_parent, f"{key}: {value.value}") tree.SetItemData(new_child, (key, value)) tree.SetItemImage( new_child, self.image_map.get(value.__class__, self.other) ) tree = wx.TreeCtrl(self, style=wx.TR_DEFAULT_STYLE | wx.EXPAND | wx.ALL) tree.AssignImageList(self.image_list) root = tree.AddRoot(root_tag_name) tree.SetItemData(root, (root_tag_name, self.nbt_data)) tree.SetItemImage( root, self.image_map.get( self.nbt_data.__class__, self.image_map[nbt.TAG_Compound] ), wx.TreeItemIcon_Normal, ) add_tree_node(tree, root, self.nbt_data) tree.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.tree_right_click) return tree def _generate_menu(self, include_add_tag=False): menu = wx.Menu() menu_items = [ wx.MenuItem(menu, text="Edit Tag", id=wx.ID_ANY), wx.MenuItem(menu, text="Delete Tag", id=wx.ID_ANY), ] if include_add_tag: menu_items.insert(0, wx.MenuItem(menu, text="Add Tag", id=wx.ID_ANY)) for menu_item in menu_items: menu.Append(menu_item) op_map = { item.GetId(): item.GetItemLabelText().split()[0].lower() for item in menu_items } menu.Bind(wx.EVT_MENU, lambda evt: self.popup_menu_handler(op_map, evt)) return menu def tree_right_click(self, evt): tag_name, tag_obj = self.tree.GetItemData(evt.GetItem()) menu = self._generate_menu( isinstance(tag_obj, (MutableMapping, MutableSequence)) ) self.PopupMenu(menu, evt.GetPoint()) menu.Destroy() evt.Skip() def popup_menu_handler(self, op_map, evt): op_id = evt.GetId() op_name = op_map[op_id] if op_name == "add": self.add_tag() elif op_name == "edit": self.edit_tag() else: selected_tag = self.tree.GetFocusedItem() if selected_tag == self.tree.GetRootItem(): wx.MessageBox("Root nodes cannot be deleted currently", "Info", wx.OK) return name, _ = self.tree.GetItemData(selected_tag) parent = self.tree.GetItemParent(selected_tag) if parent == self.tree.GetRootItem(): parent_data = self.nbt_data else: _, parent_data = self.tree.GetItemData(parent) del parent_data[name] self.tree.Delete(selected_tag) def add_tag(self): selected_tag = self.tree.GetFocusedItem() name, data = self.tree.GetItemData(selected_tag) def save_func(new_name, new_tag_value, new_tag_type, _): tag_type = [ tag_class for tag_class in self.image_map if tag_class.__name__ == new_tag_type ][0] self.nbt_data[new_name] = nbt_tag = tag_type(new_tag_value) new_child = self.tree.AppendItem( selected_tag, f"{new_name}: {new_tag_value}" ) self.tree.SetItemImage(new_child, self.image_map.get(tag_type, self.other)) self.tree.SetItemData(new_child, (new_name, nbt_tag)) add_dialog = EditTagDialog( self, "", nbt.TAG_Byte(0), [ tag_type.__name__ for tag_type in self.image_map.keys() if "TAG_" in tag_type.__name__ ], create=True, save_callback=save_func, ) add_dialog.Show() def edit_tag(self): selected_tag = self.tree.GetFocusedItem() name, data = self.tree.GetItemData(selected_tag) def save_func(new_name, new_tag_value, new_tag_type, old_name): tag_type = [ tag_class for tag_class in self.image_map if tag_class.__name__ == new_tag_type ][0] self.nbt_data[new_name] = nbt_tag = tag_type(new_tag_value) self.tree.SetItemImage( selected_tag, self.image_map.get(tag_type, self.other) ) self.tree.SetItemData(selected_tag, (new_name, nbt_tag)) self.tree.SetItemText(selected_tag, f"{new_name}: {new_tag_value}") if new_name != old_name: del self.nbt_data[old_name] edit_dialog = EditTagDialog( self, name, data, [ tag_type.__name__ for tag_type in self.image_map.keys() if "TAG_" in tag_type.__name__ ], save_callback=save_func, ) edit_dialog.Show() class EditTagDialog(wx.Frame): GRID_ROWS = 3 GRID_COLUMNS = 4 def __init__( self, parent, tag_name, tag, tag_types, create=False, save_callback=None ): super(EditTagDialog, self).__init__( parent, title="Edit NBT Tag", size=(500, 280) ) self.save_callback = save_callback self.old_name = tag_name self.data_type_func = lambda x: x main_panel = simple.SimplePanel(self) name_panel = simple.SimplePanel(main_panel, sizer_dir=wx.HORIZONTAL) value_panel = simple.SimplePanel(main_panel, sizer_dir=wx.HORIZONTAL) tag_type_panel = simple.SimplePanel(main_panel) button_panel = simple.SimplePanel(main_panel, sizer_dir=wx.HORIZONTAL) name_label = wx.StaticText(name_panel, label="Name: ") self.name_field = wx.TextCtrl(name_panel) if tag_name == "" and not create: self.name_field.Disable() else: self.name_field.SetValue(tag_name) name_panel.add_object(name_label, space=0, options=wx.ALL | wx.CENTER) name_panel.add_object(self.name_field, space=1, options=wx.ALL | wx.EXPAND) value_label = wx.StaticText(value_panel, label="Value: ") self.value_field = wx.TextCtrl(value_panel) if isinstance(tag, (nbt.TAG_Compound, nbt.TAG_List)): self.value_field.Disable() else: self.value_field.SetValue(str(tag.value)) value_panel.add_object(value_label, space=0, options=wx.ALL | wx.CENTER) value_panel.add_object(self.value_field, space=1, options=wx.ALL | wx.EXPAND) tag_type_sizer = wx.GridSizer(self.GRID_ROWS, self.GRID_COLUMNS, 0, 0) self.radio_buttons = [] for tag_type in tag_types: rd_btn = NBTRadioButton( tag_type_panel, tag_type, parent.image_list.GetBitmap(parent.image_map[getattr(nbt, tag_type)]), ) self.radio_buttons.append(rd_btn) rd_btn.Bind(wx.EVT_RADIOBUTTON, partial(self.handle_radio_button, tag_type)) tag_type_sizer.Add(rd_btn, 0, wx.ALL, 0) if tag_type == tag.__class__.__name__: rd_btn.SetValue(True) tag_type_panel.SetSizerAndFit(tag_type_sizer) self.save_button = wx.Button(button_panel, label="Save") self.cancel_button = wx.Button(button_panel, label="Cancel") button_panel.add_object(self.save_button, space=0) button_panel.add_object(self.cancel_button, space=0) main_panel.add_object(name_panel, space=0, options=wx.ALL | wx.EXPAND) main_panel.add_object(value_panel, space=0, options=wx.ALL | wx.EXPAND) main_panel.add_object(tag_type_panel, space=0) main_panel.add_object(button_panel, space=0) self.save_button.Bind(wx.EVT_BUTTON, self.save) self.cancel_button.Bind(wx.EVT_BUTTON, lambda evt: self.Close()) self.value_field.Bind(wx.EVT_TEXT, self.value_changed) self.SetSize((235, 260)) self.Layout() def value_changed(self, evt): tag_value = evt.GetString() self.value_field.ChangeValue(str(self.data_type_func(tag_value))) def handle_radio_button(self, tag_type, evt): for rd_btn in self.radio_buttons: rd_btn.SetValue(rd_btn.nbt_tag_class == tag_type) self.change_tag_type_func(tag_type) def change_tag_type_func(self, tag_type): self.data_type_func = lambda x: x if tag_type in ("TAG_Int", "TAG_Long", "TAG_Short", "TAG_Short", "TAG_Byte"): self.data_type_func = lambda x: int(float(x)) elif tag_type in ("TAG_Float", "TAG_Double"): self.data_type_func = float if tag_type not in ("TAG_Byte_Array", "TAG_Int_Array", "TAG_Long_Array"): self.value_field.ChangeValue( str(self.data_type_func(self.value_field.GetValue())) ) def get_selected_tag_type(self): for rd_btn in self.radio_buttons: if rd_btn.GetValue(): return rd_btn.nbt_tag_class return None def save(self, evt): self.save_callback( self.name_field.GetValue(), self.data_type_func(self.value_field.GetValue()), self.get_selected_tag_type(), self.old_name, ) self.Close() if __name__ == "__main__": import wx.lib.inspection app = wx.App() wx.lib.inspection.InspectionTool().Show() frame = wx.Frame(None) NBTEditor(frame, nbt.load(NBT_FILE), callback=lambda nbt_data: print(nbt_data)) frame.Show() app.MainLoop()
Amulet-Map-Editor
amulet_map_editor\api\wx\ui\select_world.py
import os import wx import glob from sys import platform from typing import List, Dict, Tuple, Callable, TYPE_CHECKING import traceback import logging from amulet import load_format from amulet.api.errors import FormatError from amulet_map_editor import lang, CONFIG from amulet_map_editor.api.wx.ui import simple from amulet_map_editor.api.wx.util.ui_preferences import preserve_ui_preferences from amulet_map_editor.api.framework import app if TYPE_CHECKING: from amulet.api.wrapper import WorldFormatWrapper log = logging.getLogger(__name__) # Windows %APPDATA%\.minecraft # macOS ~/Library/Application Support/minecraft # Linux ~/.minecraft minecraft_world_paths: list[tuple[str, str]] = [] if platform == "win32": minecraft_world_paths.append( ( lang.get("world.java_platform"), os.path.join(os.getenv("APPDATA"), ".minecraft", "saves"), ) ) minecraft_world_paths.append( ( lang.get("world.bedrock_uwp"), os.path.join( os.getenv("LOCALAPPDATA"), "Packages", "Microsoft.MinecraftUWP_8wekyb3d8bbwe", "LocalState", "games", "com.mojang", "minecraftWorlds", ), ) ) minecraft_world_paths.append( ( lang.get("world.bedrock_uwp_beta"), os.path.join( os.getenv("LOCALAPPDATA"), "Packages", "Microsoft.MinecraftWindowsBeta_8wekyb3d8bbwe", "LocalState", "games", "com.mojang", "minecraftWorlds", ), ) ) minecraft_world_paths.append( ( lang.get("world.bedrock_education_store"), os.path.join( os.getenv("LOCALAPPDATA"), "Packages", "Microsoft.MinecraftEducationEdition_8wekyb3d8bbwe", "LocalState", "games", "com.mojang", "minecraftWorlds", ), ) ) minecraft_world_paths.append( ( lang.get("world.bedrock_education_desktop"), os.path.join( os.getenv("APPDATA"), "Minecraft Education Edition", "games", "com.mojang", "minecraftWorlds", ), ) ) minecraft_world_paths.append( ( lang.get("world.bedrock_netease"), os.path.join( os.getenv("APPDATA"), "MinecraftPE_Netease", "minecraftWorlds", ), ) ) for group, key in ( ("Minecraft Bedrock", "world.bedrock_gdk"), ("Minecraft Bedrock Preview", "world.bedrock_gdk_preview"), ): for worlds_path in glob.glob( os.path.join( glob.escape(os.getenv("APPDATA")), group, "Users", "*", "games", "com.mojang", "minecraftWorlds", ) ): user_id = worlds_path.split(os.sep)[-4] minecraft_world_paths.append( ( f"{lang.get(key)} {user_id}", worlds_path, ) ) elif platform == "darwin": minecraft_world_paths.append( ( lang.get("world.java_platform"), os.path.join( os.path.expanduser("~"), "Library", "Application Support", "minecraft", "saves", ), ) ) elif platform == "linux": minecraft_world_paths.append( ( lang.get("world.java_platform"), os.path.join(os.path.expanduser("~"), ".minecraft", "saves"), ) ) world_images: Dict[str, Tuple[int, wx.Bitmap, int]] = {} def get_world_image(image_path: str) -> Tuple[wx.Bitmap, int]: if ( image_path not in world_images or world_images[image_path][0] != os.stat(image_path)[8] ): img = wx.Image(image_path, wx.BITMAP_TYPE_ANY) width = min(int((img.GetWidth() / img.GetHeight()) * 128), 300) world_images[image_path] = ( os.stat(image_path)[8], img.Scale(width, 128, wx.IMAGE_QUALITY_NEAREST).ConvertToBitmap(), width, ) return world_images[image_path][1:3] class WorldUI(wx.Panel): """A Panel UI element with the world image, name and description""" def __init__(self, parent: wx.Window, world_format: "WorldFormatWrapper"): super().__init__(parent) self.SetWindowStyle(wx.TAB_TRAVERSAL | wx.BORDER_RAISED) sizer = wx.BoxSizer(wx.HORIZONTAL) self.SetSizer(sizer) img, width = get_world_image(world_format.world_image_path) self.img = wx.StaticBitmap(self, wx.ID_ANY, img, (0, 0), (width, 128)) sizer.Add(self.img) self.world_name = wx.StaticText( self, label="\n".join( [ world_format.level_name, world_format.game_version_string, os.path.join( *os.path.normpath(world_format.path).split(os.sep)[-3:] ), ] ), ) sizer.Add(self.world_name, 0, wx.ALL | wx.ALIGN_CENTER, 5) class WorldUIButton(WorldUI): """A Panel UI element that behaves like a button with the world image, name and description""" def __init__( self, parent: wx.Window, world_format: "WorldFormatWrapper", open_world_callback, ): super().__init__(parent, world_format) self.path = world_format.path self.open_world_callback = open_world_callback self.Bind(wx.EVT_LEFT_UP, self._call_callback) self.img.Bind(wx.EVT_LEFT_UP, self._call_callback) self.world_name.Bind(wx.EVT_LEFT_DOWN, self._call_callback) def _call_callback(self, evt): self.open_world_callback(self.path) class WorldList(wx.Panel): """A Panel containing zero or more `WorldUIButton`s.""" def __init__(self, parent: wx.Window, world_dirs, open_world_callback, sort=True): super().__init__(parent) sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) self.worlds = [] world_formats = [] for world_path in world_dirs: if os.path.isdir(world_path): try: world_formats.append(load_format(world_path)) except FormatError as e: log.info(f"Could not find loader for {world_path} {e}") except Exception: log.error( f"Error loading format wrapper for {world_path} {traceback.format_exc()}" ) if sort: world_formats = reversed(sorted(world_formats, key=lambda f: f.last_played)) for world_format in world_formats: try: world_button = WorldUIButton(self, world_format, open_world_callback) sizer.Add( world_button, 0, wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, 5 ) self.worlds.append(world_button) except Exception as e: log.info(f"Failed to display world button for {world_format.path} {e}") self.Layout() class CollapsibleWorldListUI(wx.CollapsiblePane): """a drop down list of `WorldUIButton`s for a given directory""" def __init__(self, parent, paths: List[str], group_name: str, open_world_callback): super().__init__(parent, label=group_name) self.parent = parent self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.eval_layout) self.sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self.sizer) panel = self.GetPane() panel.sizer = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(panel.sizer) panel.sizer.Add(WorldList(panel, paths, open_world_callback), 0, wx.EXPAND) def eval_layout(self, evt): self.Layout() self.parent.FitInside() evt.Skip() class ScrollableWorldsUI(simple.SimpleScrollablePanel): # a frame to allow scrolling def __init__(self, parent, open_world_callback): super(ScrollableWorldsUI, self).__init__(parent) self.open_world_callback = open_world_callback self.dirs: Dict[str, CollapsibleWorldListUI] = {} self.reload() self.Layout() def reload(self): for val in self.dirs.values(): val.Destroy() self.dirs.clear() for group_name, directory in sorted(minecraft_world_paths, key=lambda x: x[0]): if os.path.isdir(directory): world_list = CollapsibleWorldListUI( self, glob.glob(os.path.join(glob.escape(directory), "*")), group_name, self.open_world_callback, ) self.add_object(world_list, 0, wx.EXPAND) self.dirs[directory] = world_list def OnChildFocus(self, event): event.Skip() class WorldSelectUI(wx.Panel): # a frame containing a refresh button for the UI, a sort order for the worlds # and a vertical list of `WorldDirectoryUI`s for each directory # perhaps also a select directory option def __init__(self, parent, open_world_callback): super().__init__(parent) self.open_world_callback = open_world_callback sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) self.header_open_world = wx.Button( self, label=lang.get("select_world.open_world_button") ) self.header_open_world.Bind(wx.EVT_BUTTON, self._open_world) sizer.Add(self.header_open_world) content = ScrollableWorldsUI(self, open_world_callback) sizer.Add(content, 1, wx.EXPAND) def _open_world(self, evt): dir_dialog = wx.DirDialog( None, lang.get("select_world.open_world_dialogue"), "", wx.DD_DEFAULT_STYLE | wx.DD_DIR_MUST_EXIST, ) try: if dir_dialog.ShowModal() == wx.ID_CANCEL: return path = dir_dialog.GetPath() except Exception: wx.LogError(lang.get("select_world.select_directory_failed")) return finally: dir_dialog.Destroy() self.open_world_callback(path) class RecentWorldUI(wx.Panel): def __init__(self, parent, open_world_callback): super().__init__(parent) self._open_world_callback = open_world_callback self._sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self._sizer) text = wx.StaticText( self, wx.ID_ANY, lang.get("select_world.recent_worlds"), wx.DefaultPosition, wx.DefaultSize, 0, ) text.SetFont(wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL)) self._sizer.Add( text, 0, wx.ALL | wx.ALIGN_CENTER, 5, ) self._world_list = None self.rebuild() def rebuild(self, new_world: str = None): meta: dict = CONFIG.get("amulet_meta", {}) recent_worlds: list = meta.setdefault("recent_worlds", []) if new_world is not None: while new_world in recent_worlds: recent_worlds.remove(new_world) recent_worlds.insert(0, new_world) while len(recent_worlds) > 5: recent_worlds.pop(5) if self._world_list is not None: self._world_list.Destroy() self._world_list = WorldList( self, recent_worlds, self._open_world_callback, sort=False ) self._sizer.Add(self._world_list, 1, wx.EXPAND, 5) self.Layout() CONFIG.put("amulet_meta", meta) class WorldSelectAndRecentUI(wx.Panel): def __init__(self, parent, open_world_callback): super(WorldSelectAndRecentUI, self).__init__(parent, wx.HORIZONTAL) self._open_world_callback = open_world_callback sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) warning_text = wx.StaticText( self, label=lang.get("select_world.open_world_warning"), ) warning_text.SetFont(wx.Font(20, wx.DEFAULT, wx.NORMAL, wx.NORMAL)) sizer.Add(warning_text, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.TOP, 5) # bar bottom_sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(bottom_sizer, 1, wx.EXPAND) left_sizer = wx.BoxSizer(wx.VERTICAL) bottom_sizer.Add(left_sizer, 1, wx.EXPAND) select_world = WorldSelectUI(self, self._update_recent) left_sizer.Add(select_world, 1, wx.ALL | wx.EXPAND, 5) right_sizer = wx.BoxSizer(wx.VERTICAL) bottom_sizer.Add(right_sizer, 1, wx.EXPAND) self._recent_worlds = RecentWorldUI(self, self._update_recent) right_sizer.Add(self._recent_worlds, 1, wx.EXPAND, 5) def _update_recent(self, path): self._recent_worlds.rebuild(path) self._open_world_callback(path) @preserve_ui_preferences class WorldSelectDialog(wx.Dialog): def __init__(self, parent: wx.Window, open_world_callback: Callable[[str], None]): super().__init__( parent, title=lang.get("select_world.title"), pos=wx.Point(50, 50), size=wx.Size(*[int(s * 0.95) for s in parent.GetSize()]), style=wx.CAPTION | wx.CLOSE_BOX | wx.MAXIMIZE_BOX # | wx.MAXIMIZE | wx.SYSTEM_MENU | wx.TAB_TRAVERSAL | wx.CLIP_CHILDREN | wx.RESIZE_BORDER, ) self.Bind(wx.EVT_CLOSE, self._hide_event) self._open_world_callback = open_world_callback self.world_select = WorldSelectAndRecentUI(self, self._run_callback) def _run_callback(self, path): self._close() self._open_world_callback(path) def _hide_event(self, evt): self._close() evt.Skip() def _close(self): if self.IsModal(): self.EndModal(0) else: self.Close() def open_level_from_dialog(parent: wx.Window): """Show the open world dialog and open the selected world.""" select_world = WorldSelectDialog(parent, app.open_level) select_world.ShowModal() select_world.Destroy()
Amulet-Map-Editor
amulet_map_editor\api\wx\ui\simple.py
"""A collection of classes for wx objects to abstract away the repeated code and make working with wx a bit more simple.""" import logging import wx from wx.lib.scrolledpanel import ScrolledPanel from typing import Iterable, Union, Any, List, Optional, Sequence, Dict, Tuple log = logging.getLogger(__name__) class SimpleSizer: def __init__(self, sizer_dir=wx.VERTICAL): self._sizer = self.sizer = wx.BoxSizer(sizer_dir) def add_object(self, obj, space=1, options=wx.ALL): self.sizer.Add(obj, space, options, 5) class SimplePanel(wx.Panel, SimpleSizer): def __init__(self, parent: wx.Window, sizer_dir=wx.VERTICAL): wx.Panel.__init__( self, parent, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL, ) SimpleSizer.__init__(self, sizer_dir) self.SetSizer(self.sizer) class SimpleScrollablePanel(ScrolledPanel, SimpleSizer): """A scrolled panel that automatically sets itself up.""" def __init__(self, parent: wx.Window, sizer_dir=wx.VERTICAL, **kwargs): ScrolledPanel.__init__(self, parent, **kwargs) SimpleSizer.__init__(self, sizer_dir) self.SetSizer(self.sizer) self.SetupScrolling() self.SetAutoLayout(1) def DoGetBestSize(self): sizer = self.GetSizer() if sizer is None: return -1, -1 else: sx, sy = sizer.CalcMin() return ( sx + wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X), sy, ) class SimpleChoice(wx.Choice): """A wrapper for wx.Choice that sets up the UI for you.""" def __init__( self, parent: wx.Window, choices: Sequence[str] = (), default: Optional[str] = None, ): super().__init__(parent, choices=choices) if choices: if default is not None and default in choices: self.SetSelection(choices.index(default)) else: self.SetSelection(0) def GetCurrentString(self) -> str: return self.GetString(self.GetSelection()) StringableType = Any class SimpleChoiceAny(wx.Choice): """An extension for wx.Choice that enables showing and returning objects that are not strings.""" def __init__(self, parent: wx.Window, sort=True, reverse=False): super().__init__(parent) self._values: List[Any] = [] # the data hidden behind the string self._keys: List[str] = [] # the strings shown to the user self._sorted = sort self._reverse = reverse @property def keys(self) -> Tuple[str, ...]: """Get the string values displayed to the user""" return tuple(self._keys) @property def values(self) -> Tuple[Any, ...]: """Get the data hidden behind the string value""" return tuple(self._values) @property def items(self) -> Tuple[Tuple[str, Any], ...]: """Get the string value and the data hidden behind the value""" return tuple(zip(self._keys, self._values)) def SetItems( self, items: Union[Iterable[StringableType], Dict[StringableType, Any]], default: StringableType = None, ): """Set items. Does not have to be strings. If items is a dictionary the string of the values are show to the user and the key is returned from GetAny If it is just an iterable the string of the values are shown and the raw equivalent input is returned. """ if not items: return if isinstance(items, dict): items: List[Tuple[str, Any]] = [ (str(value), key) for key, value in items.items() ] if self._sorted: items = sorted(items, key=lambda x: x[0], reverse=self._reverse) self._keys = [key.strip() for key, _ in items] self._values = [value for _, value in items] else: if self._sorted: self._values = list(sorted(items)) if self._reverse: self._values.reverse() else: self._values = list(items) self._keys = [str(v).strip() for v in self._values] super().SetItems(self._keys) if default is not None and default in self._values: self.SetSelection(self._values.index(default)) else: self.SetSelection(0) def SetValue(self, value: Any): if value in self._keys: self.SetSelection(self._keys.index(value)) def GetAny(self) -> Optional[Any]: """Return the value currently selected in the form before it was converted to a string""" log.warning( "SimpleChoiceAny.GetAny is being depreciated and will be removed in the future. Please use SimpleChoiceAny.GetCurrentObject instead", exc_info=True, ) return self.GetCurrentObject() def GetCurrentObject(self) -> Optional[Any]: """Return the value currently selected in the form before it was converted to a string""" if self._values: return self._values[self.GetSelection()] def GetCurrentString(self) -> str: """Get the string form of the value currently selected.""" return self.GetString(self.GetSelection()) class SimpleDialog(wx.Dialog): """A dialog with ok and cancel buttons set up.""" def __init__(self, parent: wx.Window, title, sizer_dir=wx.VERTICAL): wx.Dialog.__init__( self, parent, title=title, style=wx.CAPTION | wx.RESIZE_BORDER ) sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) self.sizer = wx.BoxSizer(sizer_dir) sizer.Add(self.sizer, 1, wx.EXPAND) self.bottom_sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(self.bottom_sizer, 0, wx.EXPAND) self.bottom_sizer.AddStretchSpacer() button_sizer = self.CreateButtonSizer(wx.OK | wx.CANCEL) self.bottom_sizer.Add(button_sizer, flag=wx.ALL, border=5)
Amulet-Map-Editor
amulet_map_editor\api\wx\ui\traceback_dialog.py
from typing import Optional import wx from amulet_map_editor.api import image class TracebackDialog(wx.Dialog): def __init__( self, parent: Optional[wx.Window], title: str, error: str, traceback: str, **kwargs, ): kwargs["style"] = ( kwargs.get("style", 0) | wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER ) wx.Dialog.__init__(self, parent, **kwargs) self.SetTitle(title) self._error = error self._traceback = traceback main_sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(main_sizer) error_sizer = wx.BoxSizer(wx.HORIZONTAL) main_sizer.Add(error_sizer, 0, wx.EXPAND | wx.ALL, 5) bitmap_1 = wx.StaticBitmap( self, bitmap=image.icon.tablericons.alert_circle.bitmap(32, 32) ) error_sizer.Add(bitmap_1, 0, 0, 0) error_text = wx.StaticText(self, wx.ID_ANY, error) error_sizer.Add(error_text, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5) traceback_text = wx.TextCtrl( self, wx.ID_ANY, traceback, style=wx.TE_MULTILINE | wx.TE_READONLY, size=(800, -1), ) main_sizer.Add(traceback_text, 1, wx.EXPAND, 0) button_sizer = wx.StdDialogButtonSizer() main_sizer.Add(button_sizer, 0, wx.ALIGN_RIGHT | wx.ALL, 4) copy_button = wx.Button(self, wx.ID_ANY, "Copy Error") copy_button.Bind(wx.EVT_BUTTON, self._on_copy_error) button_sizer.Add(copy_button, 0, 0, 0) button_ok = wx.Button(self, wx.ID_OK, "") button_ok.SetDefault() button_sizer.AddButton(button_ok) button_sizer.Realize() main_sizer.Fit(self) self.SetAffirmativeId(button_ok.GetId()) self.Fit() self.Layout() def _on_copy_error(self, evt): if wx.TheClipboard.Open(): wx.TheClipboard.SetData( wx.TextDataObject(f"{self._error}\n{self._traceback}") ) wx.TheClipboard.Close() class MyApp(wx.App): def OnInit(self): import traceback as traceback_ try: raise Exception("Exception message") except Exception as e: err = str(e) tb = traceback_.format_exc() self.dialog = TracebackDialog(None, "title", err, tb) self.SetTopWindow(self.dialog) self.dialog.ShowModal() self.dialog.Destroy() return True if __name__ == "__main__": app = MyApp(0) app.MainLoop()
Amulet-Map-Editor
amulet_map_editor\api\wx\ui\version_select.py
from amulet_map_editor.api.wx.ui.simple import SimpleChoice, SimpleChoiceAny import wx from wx.lib import newevent import PyMCTranslate from typing import Tuple, Optional, Type, Any from amulet.api.data_types import VersionNumberTuple, PlatformType ( PlatformChangeEvent, EVT_PLATFORM_CHANGE, ) = newevent.NewCommandEvent() # the platform entry changed ( VersionNumberChangeEvent, EVT_VERSION_NUMBER_CHANGE, ) = newevent.NewCommandEvent() # the version number entry changed ( FormatChangeEvent, EVT_FORMAT_CHANGE, ) = ( newevent.NewCommandEvent() ) # the format entry changed (is fired even if the entry isn't visible) ( VersionChangeEvent, EVT_VERSION_CHANGE, ) = ( newevent.NewCommandEvent() ) # one of the above changed. Fired after EVT_FORMAT_CHANGE class PlatformSelect(wx.Panel): def __init__( self, parent: wx.Window, translation_manager: PyMCTranslate.TranslationManager, platform: PlatformType = None, allow_universal: bool = True, allow_vanilla: bool = True, allowed_platforms: Tuple[PlatformType, ...] = None, **kwargs ): super().__init__(parent, style=wx.BORDER_SIMPLE) self._sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self._sizer) self._translation_manager = translation_manager self._allow_universal = allow_universal self._allow_vanilla = allow_vanilla self._allowed_platforms = allowed_platforms self._platform_choice: SimpleChoice = self._add_ui_element( "Platform:", SimpleChoice ) self._populate_platform() self._set_platform(platform) self._platform_choice.Bind( wx.EVT_CHOICE, lambda evt: wx.PostEvent( self, PlatformChangeEvent(self.GetId(), platform=self.platform) ), ) def _add_ui_element( self, label: str, obj: Type[wx.Control], shown=True, **kwargs ) -> Any: sizer = wx.BoxSizer(wx.HORIZONTAL) self._sizer.Add(sizer, 0, wx.EXPAND | wx.ALL, 5) text = wx.StaticText(self, label=label, style=wx.ALIGN_CENTER) sizer.Add(text, 1) wx_obj = obj(self, **kwargs) sizer.Add(wx_obj, 2) if not shown: text.Hide() wx_obj.Hide() return wx_obj @property def platform(self) -> PlatformType: return self._platform_choice.GetCurrentString() @platform.setter def platform(self, platform: PlatformType): self._set_platform(platform) wx.PostEvent(self, PlatformChangeEvent(self.GetId(), platform=self.platform)) def _set_platform(self, platform: PlatformType): if platform and platform in self._platform_choice.GetItems(): self._platform_choice.SetSelection( self._platform_choice.GetItems().index(platform) ) else: self._platform_choice.SetSelection(0) def _populate_platform(self): platforms = self._translation_manager.platforms() if self._allowed_platforms is not None: platforms = [p for p in platforms if p in self._allowed_platforms] if not self._allow_universal: platforms = [p for p in platforms if p != "universal"] if not self._allow_vanilla: platforms = [p for p in platforms if p == "universal"] self._platform_choice.SetItems(platforms) class VersionSelect(PlatformSelect): def __init__( self, parent: wx.Window, translation_manager: PyMCTranslate.TranslationManager, platform: PlatformType = None, version_number: VersionNumberTuple = None, force_blockstate: bool = None, show_force_blockstate: bool = True, allow_numerical: bool = True, allow_blockstate: bool = True, **kwargs ): super().__init__(parent, translation_manager, platform, **kwargs) self._allow_numerical = allow_numerical self._allow_blockstate = allow_blockstate self.Bind(EVT_PLATFORM_CHANGE, self._on_platform_change) self._version_choice: Optional[SimpleChoiceAny] = self._add_ui_element( "Version:", SimpleChoiceAny, reverse=True ) self._populate_version() self._set_version_number(version_number) self._version_choice.Bind( wx.EVT_CHOICE, lambda evt: wx.PostEvent( self, VersionNumberChangeEvent( self.GetId(), version_number=self.version_number ), ), ) self.Bind(EVT_VERSION_NUMBER_CHANGE, self._on_version_number_change) self._blockstate_choice: Optional[SimpleChoice] = self._add_ui_element( "Format:", SimpleChoice, shown=show_force_blockstate ) self._blockstate_choice.SetItems(["native", "blockstate"]) self._blockstate_choice.SetSelection(0) self._populate_blockstate() self._set_force_blockstate(force_blockstate) self._blockstate_choice.Bind( wx.EVT_CHOICE, lambda evt: self._post_version_change() ) def _post_version_change(self): wx.PostEvent( self, FormatChangeEvent(self.GetId(), force_blockstate=self.force_blockstate), ), wx.PostEvent( self, VersionChangeEvent( self.GetId(), platform=self.platform, version_number=self.version_number, force_blockstate=self.force_blockstate, ), ) @property def version_number(self) -> VersionNumberTuple: return self._version_choice.GetCurrentObject() @version_number.setter def version_number(self, version_number: VersionNumberTuple): self._set_version_number(version_number) wx.PostEvent( self, VersionNumberChangeEvent(self.GetId(), version_number=self.version_number), ) def _set_version_number(self, version_number: VersionNumberTuple): if version_number and version_number in self._version_choice.values: self._version_choice.SetSelection( self._version_choice.values.index(version_number) ) else: self._version_choice.SetSelection(0) @property def force_blockstate(self) -> bool: return self._blockstate_choice.GetCurrentString() == "blockstate" @force_blockstate.setter def force_blockstate(self, force_blockstate: bool): self._set_force_blockstate(force_blockstate) self._post_version_change() def _set_force_blockstate(self, force_blockstate: bool): if force_blockstate is not None: self._blockstate_choice.SetSelection(int(force_blockstate)) @property def version(self) -> Tuple[PlatformType, VersionNumberTuple, bool]: return self.platform, self.version_number, self.force_blockstate @version.setter def version(self, version: Tuple[PlatformType, VersionNumberTuple, bool]): platform, version_number, force_blockstate = version self._set_platform(platform) self._set_version_number(version_number) self.force_blockstate = force_blockstate def _populate_version(self): versions = self._translation_manager.version_numbers(self.platform) if not self._allow_blockstate: versions = [v for v in versions if v < (1, 13, 0)] if not self._allow_numerical: versions = [v for v in versions if v >= (1, 13, 0)] self._version_choice.SetItems(versions) def _populate_blockstate(self): if self._translation_manager.get_version( self.platform, self.version_number ).has_abstract_format: self._blockstate_choice.Enable() else: self._blockstate_choice.Disable() def _on_platform_change(self, evt): self._populate_version() self.version_number = None evt.Skip() def _on_version_number_change(self, evt): self._populate_blockstate() self.force_blockstate = None evt.Skip() if __name__ == "__main__": def main(): translation_manager = PyMCTranslate.new_translation_manager() app = wx.App() for cls in ( PlatformSelect, VersionSelect, lambda *args: VersionSelect(*args, show_force_blockstate=False), ): dialog = wx.Dialog(None) sizer = wx.BoxSizer() dialog.SetSizer(sizer) sizer.Add(cls(dialog, translation_manager)) dialog.Show() dialog.Fit() app.MainLoop() main()
Amulet-Map-Editor
amulet_map_editor\api\wx\ui\__init__.py
Amulet-Map-Editor
amulet_map_editor\api\wx\util\button_input.py
import wx from typing import Set, Dict, Tuple from .window_container import WindowContainer from .key_config import KeyType, serialise_key, KeybindGroup ActionIDType = str _InputPressEventType = wx.NewEventType() EVT_INPUT_PRESS = wx.PyEventBinder(_InputPressEventType) class InputPressEvent(wx.PyEvent): """An action run by a button being pressed.""" def __init__(self, action_id: ActionIDType): wx.PyEvent.__init__(self, eventType=_InputPressEventType) self._action_id = action_id @property def action_id(self) -> ActionIDType: """The string id of the action triggered by the keypress""" return self._action_id _InputReleaseEventType = wx.NewEventType() EVT_INPUT_RELEASE = wx.PyEventBinder(_InputReleaseEventType) class InputReleaseEvent(wx.PyEvent): """An action run by a button being released.""" def __init__(self, action_id: ActionIDType): wx.PyEvent.__init__(self, eventType=_InputReleaseEventType) self._action_id = action_id @property def action_id(self) -> ActionIDType: """The string id of the action triggered by the key release""" return self._action_id _InputHeldEventType = wx.NewEventType() EVT_INPUT_HELD = wx.PyEventBinder(_InputHeldEventType) class InputHeldEvent(wx.PyEvent): """An action run by a button being held. This action will run frequently.""" def __init__(self, action_ids: Set[ActionIDType]): wx.PyEvent.__init__(self, eventType=_InputHeldEventType) self._action_ids = action_ids @property def action_ids(self) -> Set[ActionIDType]: """The string ids of the actions that have been held.""" return self._action_ids class Action: """A private class for helping with key management for an action.""" def __init__(self, trigger_key: KeyType, modifier_keys: Tuple[KeyType, ...]): self._required_keys = set(modifier_keys + (trigger_key,)) self._trigger_key = trigger_key self._modifier_keys = set(modifier_keys) @property def required_keys(self) -> Set[KeyType]: """The keys that need to remain pressed for this action to stay active.""" return self._required_keys @property def trigger_key(self) -> KeyType: """The key that needs pressing for this action to start.""" return self._trigger_key @property def modifier_keys(self) -> Set[KeyType]: """Additional keys that must already be pressed for this action to start.""" return self._modifier_keys class ButtonInput(WindowContainer): """A class to detect and store user inputs.""" def __init__(self, window: wx.Window): super().__init__(window) self._registered_actions: Dict[ActionIDType, Action] = {} self._pressed_keys: Set[KeyType] = set() # The actions that have been started but not stopped. self._continuous_actions: Set[ActionIDType] = set() # timer to deal with persistent actions self._input_timer = wx.Timer(self.window) def bind_events(self): """Set up all events required to run.""" # key press actions self.window.Bind(wx.EVT_LEFT_DOWN, self._press) self.window.Bind(wx.EVT_LEFT_UP, self._release) self.window.Bind(wx.EVT_MIDDLE_DOWN, self._press) self.window.Bind(wx.EVT_MIDDLE_UP, self._release) self.window.Bind(wx.EVT_RIGHT_DOWN, self._press) self.window.Bind(wx.EVT_RIGHT_UP, self._release) self.window.Bind(wx.EVT_KEY_DOWN, self._press) self.window.Bind(wx.EVT_KEY_UP, self._release) self.window.Bind(wx.EVT_NAVIGATION_KEY, self._release) self.window.Bind(wx.EVT_NAVIGATION_KEY, self._press) self.window.Bind(wx.EVT_MOUSEWHEEL, self._release) self.window.Bind(wx.EVT_MOUSEWHEEL, self._press) self.window.Bind(wx.EVT_MOUSE_AUX1_DOWN, self._press) self.window.Bind(wx.EVT_MOUSE_AUX1_UP, self._release) self.window.Bind(wx.EVT_MOUSE_AUX2_DOWN, self._press) self.window.Bind(wx.EVT_MOUSE_AUX2_UP, self._release) self.window.Bind( wx.EVT_TIMER, self._process_continuous_inputs, self._input_timer ) # save destruction self.window.Bind(wx.EVT_WINDOW_DESTROY, self._on_destroy, self.window) def enable(self): self._input_timer.Start(33) def disable(self): self._input_timer.Stop() def _on_destroy(self, evt): self.disable() evt.Skip() @property def pressed_keys(self) -> Set[KeyType]: """A tuple of all the keys that are currently pressed.""" return self._pressed_keys.copy() @property def pressed_actions(self) -> Set[ActionIDType]: return self._continuous_actions.copy() def is_key_pressed(self, key: KeyType): """Is the requested key currently in the pressed state.""" return key in self._pressed_keys def unpress_all(self): """Unpress all keys. This is useful if the window focus is lost because key release events will not be detected. """ self._pressed_keys.clear() self._clean_up_actions() def clear_registered_actions(self): """Clear the previously registered actions so that they can be repopulated.""" self._registered_actions.clear() self._continuous_actions.clear() def action_id_registered(self, action_id: ActionIDType): """Has the action id already been registered.""" return action_id in self._registered_actions def register_action( self, action_id: ActionIDType, modifier_keys: Tuple[KeyType, ...], trigger_key: KeyType, ): """Register a new action for the given trigger key and optional modifier keys. This action will be fired when the trigger key is pressed providing all the modifier keys are already pressed. :param action_id: The unique action id. Will raise a ValueError if it is already taken. :param modifier_keys: Other keys that need to be pressed for the action to happen. :param trigger_key: The key that when pressed will start the action provided the modifier keys are pressed. :return: """ if not isinstance(action_id, str): raise TypeError("action_id must be a string.") if ( not isinstance(trigger_key, (str, int)) or not isinstance(modifier_keys, tuple) or not all(isinstance(k, (str, int)) for k in modifier_keys) ): raise TypeError( "The key inputs are not of the correct format. Expected Union[str, int], Tuple[Union[str, int], ...]" ) if self.action_id_registered(action_id): raise ValueError(f"{action_id} has already been registered.") self._registered_actions[action_id] = Action(trigger_key, modifier_keys) def register_actions(self, actions: KeybindGroup): for action_id, (modifier_keys, trigger_key) in actions.items(): self.register_action(action_id, modifier_keys, trigger_key) def _find_actions(self, key: KeyType) -> Tuple[ActionIDType, ...]: """A method to find all actions triggered by `key` with the modifier keys also pressed.""" return tuple( action_id for action_id, action in self._registered_actions.items() if action.trigger_key == key and action.modifier_keys.issubset(self._pressed_keys) ) def _press(self, evt): """Event to handle a number of different key presses""" key = serialise_key(evt) if key is None: return if not self.is_key_pressed(key): action_ids = self._find_actions(key) self._continuous_actions.update(action_ids) for action_id in action_ids: wx.PostEvent(self.window, InputPressEvent(action_id)) self._pressed_keys.add(key) evt.Skip() def _release(self, evt): """Event to handle a number of different key releases""" key = serialise_key(evt) if key is None: return if self.is_key_pressed(key): # remove the pressed key self._pressed_keys.remove(key) self._clean_up_actions() evt.Skip() def _clean_up_actions(self): # find all actions that are now not valid and remove them for action_id in list(self._continuous_actions): if not self._registered_actions[action_id].required_keys.issubset( self._pressed_keys ): self._continuous_actions.remove(action_id) wx.PostEvent(self.window, InputReleaseEvent(action_id)) def _process_continuous_inputs(self, evt): wx.PostEvent(self.window, InputHeldEvent(self._continuous_actions.copy()))
Amulet-Map-Editor
amulet_map_editor\api\wx\util\key_config.py
import wx from amulet_map_editor.api.wx.ui.simple import ( SimpleDialog, SimpleScrollablePanel, SimpleChoice, ) from typing import Dict, Tuple, Optional, Union, Sequence from amulet_map_editor.api.image import ADD_ICON, SUBTRACT_ICON, EDIT_ICON ModifierKeyType = str KeyType = Union[int, str] KeybindGroupIdType = str KeyActionType = str ModifierType = Tuple[ModifierKeyType, ...] SerialisedKeyType = Tuple[ModifierType, KeyType] KeybindGroup = Dict[KeyActionType, SerialisedKeyType] ActionLookupType = Dict[SerialisedKeyType, KeyActionType] KeybindContainer = Dict[KeybindGroupIdType, KeybindGroup] MouseLeft = "MOUSE_LEFT" MouseMiddle = "MOUSE_MIDDLE" MouseRight = "MOUSE_RIGHT" MouseAux1 = "MOUSE_AUX_1" MouseAux2 = "MOUSE_AUX_2" MouseWheelScrollUp = "MOUSE_WHEEL_SCROLL_UP" MouseWheelScrollDown = "MOUSE_WHEEL_SCROLL_DOWN" Control = "CTRL" Shift = "SHIFT" Alt = "ALT" Space = "SPACE" PageUp = "PAGE_UP" PageDown = "PAGE_DOWN" Back = "BACK" Tab = "TAB" Return = "RETURN" Escape = "ESCAPE" Delete = "DELETE" Start = "START" Menu = "MENU" Pause = "PAUSE" Capital = "CAPITAL" End = "END" Home = "HOME" Left = "LEFT" Up = "UP" Right = "RIGHT" Down = "DOWN" Select = "SELECT" Print = "PRINT" Execute = "EXECUTE" Snapshot = "SNAPSHOT" Insert = "INSERT" Help = "HELP" Numpad0 = "NUMPAD0" Numpad1 = "NUMPAD1" Numpad2 = "NUMPAD2" Numpad3 = "NUMPAD3" Numpad4 = "NUMPAD4" Numpad5 = "NUMPAD5" Numpad6 = "NUMPAD6" Numpad7 = "NUMPAD7" Numpad8 = "NUMPAD8" Numpad9 = "NUMPAD9" Multiply = "MULTIPLY" Add = "ADD" Separator = "SEPARATOR" Subtract = "SUBTRACT" Decimal = "DECIMAL" Divide = "DIVIDE" F1 = "F1" F2 = "F2" F3 = "F3" F4 = "F4" F5 = "F5" F6 = "F6" F7 = "F7" F8 = "F8" F9 = "F9" F10 = "F10" F11 = "F11" F12 = "F12" F13 = "F13" F14 = "F14" F15 = "F15" F16 = "F16" F17 = "F17" F18 = "F18" F19 = "F19" F20 = "F20" F21 = "F21" F22 = "F22" F23 = "F23" F24 = "F24" Numlock = "NUMLOCK" Scroll = "SCROLL" Numpad_Space = "NUMPAD_SPACE" Numpad_Tab = "NUMPAD_TAB" Numpad_Enter = "NUMPAD_ENTER" Numpad_F1 = "NUMPAD_F1" Numpad_F2 = "NUMPAD_F2" Numpad_F3 = "NUMPAD_F3" Numpad_F4 = "NUMPAD_F4" Numpad_Home = "NUMPAD_HOME" Numpad_Left = "NUMPAD_LEFT" Numpad_Up = "NUMPAD_UP" Numpad_Right = "NUMPAD_RIGHT" Numpad_Down = "NUMPAD_DOWN" Numpad_Pageup = "NUMPAD_PAGEUP" Numpad_Pagedown = "NUMPAD_PAGEDOWN" Numpad_End = "NUMPAD_END" Numpad_Begin = "NUMPAD_BEGIN" Numpad_Insert = "NUMPAD_INSERT" Numpad_Delete = "NUMPAD_DELETE" Numpad_Equal = "NUMPAD_EQUAL" Numpad_Multiply = "NUMPAD_MULTIPLY" Numpad_Add = "NUMPAD_ADD" Numpad_Separator = "NUMPAD_SEPARATOR" Numpad_Subtract = "NUMPAD_SUBTRACT" Numpad_Decimal = "NUMPAD_DECIMAL" Numpad_Divide = "NUMPAD_DIVIDE" key_string_map = { wx.WXK_CONTROL: Control, wx.WXK_SHIFT: Shift, wx.WXK_ALT: Alt, wx.WXK_SPACE: Space, wx.WXK_PAGEUP: PageUp, wx.WXK_PAGEDOWN: PageDown, wx.WXK_BACK: Back, wx.WXK_TAB: Tab, wx.WXK_RETURN: Return, wx.WXK_ESCAPE: Escape, wx.WXK_DELETE: Delete, wx.WXK_START: Start, wx.WXK_MENU: Menu, wx.WXK_PAUSE: Pause, wx.WXK_CAPITAL: Capital, wx.WXK_END: End, wx.WXK_HOME: Home, wx.WXK_LEFT: Left, wx.WXK_UP: Up, wx.WXK_RIGHT: Right, wx.WXK_DOWN: Down, wx.WXK_SELECT: Select, wx.WXK_PRINT: Print, wx.WXK_EXECUTE: Execute, wx.WXK_SNAPSHOT: Snapshot, wx.WXK_INSERT: Insert, wx.WXK_HELP: Help, wx.WXK_NUMPAD0: Numpad0, wx.WXK_NUMPAD1: Numpad1, wx.WXK_NUMPAD2: Numpad2, wx.WXK_NUMPAD3: Numpad3, wx.WXK_NUMPAD4: Numpad4, wx.WXK_NUMPAD5: Numpad5, wx.WXK_NUMPAD6: Numpad6, wx.WXK_NUMPAD7: Numpad7, wx.WXK_NUMPAD8: Numpad8, wx.WXK_NUMPAD9: Numpad9, wx.WXK_MULTIPLY: Multiply, wx.WXK_ADD: Add, wx.WXK_SEPARATOR: Separator, wx.WXK_SUBTRACT: Subtract, wx.WXK_DECIMAL: Decimal, wx.WXK_DIVIDE: Divide, wx.WXK_F1: F1, wx.WXK_F2: F2, wx.WXK_F3: F3, wx.WXK_F4: F4, wx.WXK_F5: F5, wx.WXK_F6: F6, wx.WXK_F7: F7, wx.WXK_F8: F8, wx.WXK_F9: F9, wx.WXK_F10: F10, wx.WXK_F11: F11, wx.WXK_F12: F12, wx.WXK_F13: F13, wx.WXK_F14: F14, wx.WXK_F15: F15, wx.WXK_F16: F16, wx.WXK_F17: F17, wx.WXK_F18: F18, wx.WXK_F19: F19, wx.WXK_F20: F20, wx.WXK_F21: F21, wx.WXK_F22: F22, wx.WXK_F23: F23, wx.WXK_F24: F24, wx.WXK_NUMLOCK: Numlock, wx.WXK_SCROLL: Scroll, wx.WXK_NUMPAD_SPACE: Numpad_Space, wx.WXK_NUMPAD_TAB: Numpad_Tab, wx.WXK_NUMPAD_ENTER: Numpad_Enter, wx.WXK_NUMPAD_F1: Numpad_F1, wx.WXK_NUMPAD_F2: Numpad_F2, wx.WXK_NUMPAD_F3: Numpad_F3, wx.WXK_NUMPAD_F4: Numpad_F4, wx.WXK_NUMPAD_HOME: Numpad_Home, wx.WXK_NUMPAD_LEFT: Numpad_Left, wx.WXK_NUMPAD_UP: Numpad_Up, wx.WXK_NUMPAD_RIGHT: Numpad_Right, wx.WXK_NUMPAD_DOWN: Numpad_Down, wx.WXK_NUMPAD_PAGEUP: Numpad_Pageup, wx.WXK_NUMPAD_PAGEDOWN: Numpad_Pagedown, wx.WXK_NUMPAD_END: Numpad_End, wx.WXK_NUMPAD_BEGIN: Numpad_Begin, wx.WXK_NUMPAD_INSERT: Numpad_Insert, wx.WXK_NUMPAD_DELETE: Numpad_Delete, wx.WXK_NUMPAD_EQUAL: Numpad_Equal, wx.WXK_NUMPAD_MULTIPLY: Numpad_Multiply, wx.WXK_NUMPAD_ADD: Numpad_Add, wx.WXK_NUMPAD_SEPARATOR: Numpad_Separator, wx.WXK_NUMPAD_SUBTRACT: Numpad_Subtract, wx.WXK_NUMPAD_DECIMAL: Numpad_Decimal, wx.WXK_NUMPAD_DIVIDE: Numpad_Divide, } _mouse_events = { wx.EVT_LEFT_DOWN.evtType[0]: MouseLeft, wx.EVT_LEFT_UP.evtType[0]: MouseLeft, wx.EVT_MIDDLE_DOWN.evtType[0]: MouseMiddle, wx.EVT_MIDDLE_UP.evtType[0]: MouseMiddle, wx.EVT_RIGHT_DOWN.evtType[0]: MouseRight, wx.EVT_RIGHT_UP.evtType[0]: MouseRight, wx.EVT_MOUSE_AUX1_DOWN.evtType[0]: MouseAux1, wx.EVT_MOUSE_AUX1_UP.evtType[0]: MouseAux1, wx.EVT_MOUSE_AUX2_DOWN.evtType[0]: MouseAux2, wx.EVT_MOUSE_AUX2_UP.evtType[0]: MouseAux2, } def serialise_modifier( evt: Union[wx.KeyEvent, wx.MouseEvent], key: int ) -> ModifierType: modifier = [] if evt.ControlDown(): if key not in (wx.WXK_SHIFT, wx.WXK_ALT): # if control is pressed the real key must not be a modifier modifier.append(Control) if evt.ShiftDown(): modifier.append(Shift) if evt.AltDown(): modifier.append(Alt) return tuple(modifier) def serialise_key(evt: Union[wx.KeyEvent, wx.MouseEvent]) -> Optional[KeyType]: """Get the serialised version of the key that was pressed/released.""" if isinstance(evt, wx.KeyEvent): key = evt.GetUnicodeKey() or evt.GetKeyCode() if 33 <= key <= 126: key = chr(key).upper() elif key in key_string_map: key = key_string_map[key] else: key = f"UNKNOWN KEY {key}" return key elif isinstance(evt, wx.MouseEvent): key = evt.GetEventType() if key in wx.EVT_MOUSEWHEEL.evtType: if evt.GetWheelRotation() < 0: return MouseWheelScrollDown elif evt.GetWheelRotation() > 0: return MouseWheelScrollUp elif key in _mouse_events: return _mouse_events[key] def serialise_key_event( evt: Union[wx.KeyEvent, wx.MouseEvent], ) -> Optional[SerialisedKeyType]: if isinstance(evt, wx.KeyEvent): key = evt.GetUnicodeKey() or evt.GetKeyCode() if key == wx.WXK_CONTROL: return modifier = serialise_modifier(evt, key) if 33 <= key <= 126: key = chr(key).upper() elif key in key_string_map: key = key_string_map[key] else: key = f"UNKNOWN KEY {key}" return modifier, key elif isinstance(evt, wx.MouseEvent): key = evt.GetEventType() modifier = serialise_modifier(evt, key) if key in wx.EVT_MOUSEWHEEL.evtType: if evt.GetWheelRotation() < 0: return modifier, MouseWheelScrollDown elif evt.GetWheelRotation() > 0: return modifier, MouseWheelScrollUp elif key in _mouse_events: return modifier, _mouse_events[key] def stringify_key(key: SerialisedKeyType) -> str: return " + ".join([str(s) for s in key[0] + (key[1],)]) class KeyCatcher(wx.Dialog): def __init__(self, parent: wx.Window, action: str): super().__init__( parent, title=f"Press the key you want assigned to {action}", style=wx.DEFAULT_DIALOG_STYLE | wx.WANTS_CHARS, ) self._key = ((), "NONE") panel = wx.Panel(self) panel.SetFocus() panel.Bind(wx.EVT_LEFT_DOWN, self._on_key) panel.Bind(wx.EVT_MIDDLE_DOWN, self._on_key) panel.Bind(wx.EVT_RIGHT_DOWN, self._on_key) panel.Bind(wx.EVT_KEY_DOWN, self._on_key) panel.Bind(wx.EVT_MOUSEWHEEL, self._on_key) panel.Bind(wx.EVT_MOUSE_AUX1_DOWN, self._on_key) panel.Bind(wx.EVT_MOUSE_AUX2_DOWN, self._on_key) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(panel, 1, wx.EXPAND) self.SetSizer(sizer) self.Layout() def _on_key(self, evt): key = serialise_key_event(evt) if key is not None: self._key = key self.EndModal(1) @property def key(self) -> SerialisedKeyType: return self._key # TODO: make any key able to be a modifier. Instead of registering keys on press register them on release. # When a key is pressed store it to a set of persistent keys. When a key is released that is the triggering # key and all persistent keys are modifiers. # In the actual program detect all keys on press/release as normal but also store the set of persistent keys. # When serialising give the key that was pressed/released along with all the modifiers. # Return all actions that use the triggering key as the triggering key and use a sub-set of the persistent keys. class KeyConfigDialog(SimpleDialog): def __init__( self, parent: wx.Window, selected_group: KeybindGroupIdType, entries: Sequence[KeyActionType], fixed_keybinds: KeybindContainer, user_keybinds: KeybindContainer, ): super().__init__(parent, "Key Select") self._key_config = KeyConfig( self, selected_group, entries, fixed_keybinds, user_keybinds ) self.sizer.Add(self._key_config, 1, wx.EXPAND) self.Layout() self.Fit() @property def options(self) -> Tuple[KeybindContainer, KeybindGroupIdType, KeybindGroup]: return self._key_config.options class KeyConfig(wx.BoxSizer): def __init__( self, parent: wx.Window, selected_group: KeybindGroupIdType, entries: Sequence[KeyActionType], fixed_keybinds: KeybindContainer, user_keybinds: KeybindContainer, ): super().__init__(wx.VERTICAL) self._entries = entries self._fixed_keybinds = fixed_keybinds self._user_keybinds = user_keybinds top_sizer = wx.BoxSizer(wx.HORIZONTAL) self.Add(top_sizer, 0, wx.EXPAND) self._choice = SimpleChoice( parent, list(self._fixed_keybinds.keys()) + list(self._user_keybinds.keys()), selected_group, ) self._choice.Bind(wx.EVT_CHOICE, self._on_group_change) top_sizer.Add(self._choice, 1, wx.ALL | wx.EXPAND, 5) add = wx.BitmapButton(parent, bitmap=ADD_ICON.bitmap(32, 32)) add.Bind(wx.EVT_BUTTON, lambda evt: self._create_new_group()) top_sizer.Add(add, 0, wx.ALL, 5) self._delete = wx.BitmapButton(parent, bitmap=SUBTRACT_ICON.bitmap(32, 32)) self._delete.Bind(wx.EVT_BUTTON, lambda evt: self._delete_group()) top_sizer.Add(self._delete, 0, wx.ALL, 5) self._rename = wx.BitmapButton(parent, bitmap=EDIT_ICON.bitmap(32, 32)) self._rename.Bind(wx.EVT_BUTTON, lambda evt: self._rename_group()) top_sizer.Add(self._rename, 0, wx.ALL, 5) self._options = SimpleScrollablePanel(parent, size=(500, 500)) self.Add(self._options, 1, wx.EXPAND) grid_sizer = wx.GridSizer(len(entries), 2, 5, 5) self._options.sizer.Add(grid_sizer, 0, wx.ALL | wx.EXPAND, 5) self._key_buttons: Dict[str, wx.Button] = {} for action in entries: grid_sizer.Add( wx.StaticText(self._options, label=action.title()), 0, wx.ALIGN_CENTER ) self._key_buttons[action] = button = wx.Button(self._options) button.Bind(wx.EVT_BUTTON, lambda evt, a=action: self._modify_button(a)) grid_sizer.Add(button, 0, wx.EXPAND) self._rebuild_buttons() def _rebuild_buttons(self): group_id = self._choice.GetCurrentString() if group_id in self._fixed_keybinds: group = self._fixed_keybinds[group_id] self._delete.Disable() self._rename.Disable() else: group = self._user_keybinds[group_id] self._delete.Enable() self._rename.Enable() for action in self._entries: self._key_buttons[action].SetLabel( stringify_key(group.get(action, ((), "NONE"))) ) def _rebuild_choice(self, group_name=None): index = self._choice.GetSelection() self._choice.SetItems( list(self._fixed_keybinds.keys()) + list(self._user_keybinds.keys()) ) if group_name is not None: self._choice.SetSelection(self._choice.FindString(group_name)) else: self._choice.SetSelection(max(index - 1, 0)) self._rebuild_buttons() def _delete_group(self): group = self._choice.GetCurrentString() if group in self._user_keybinds: del self._user_keybinds[group] self._rebuild_choice() def _request_group_name(self) -> Optional[str]: group_name = "" while group_name == "": msg = wx.TextEntryDialog(self._options, "Enter a new group name.") if msg.ShowModal() == wx.ID_OK: group_name = msg.GetValue() if ( group_name in self._fixed_keybinds or group_name in self._user_keybinds ): group_name = "" else: return return group_name def _rename_group(self): old_group_name = self._choice.GetCurrentString() if old_group_name in self._user_keybinds: group_name = self._request_group_name() if group_name is None: return group = self._user_keybinds[old_group_name] del self._user_keybinds[old_group_name] self._user_keybinds[group_name] = group self._rebuild_choice(group_name) def _create_new_group(self): group_name = self._request_group_name() if group_name is None: return old_group_name = self._choice.GetCurrentString() if old_group_name in self._fixed_keybinds: group = self._fixed_keybinds[old_group_name] else: group = self._user_keybinds[old_group_name] self._user_keybinds[group_name] = group.copy() self._rebuild_choice(group_name) def _modify_button(self, action): if self._choice.GetCurrentString() in self._fixed_keybinds: msg = wx.MessageDialog( self._options, "The active key group is not editable. Would you like to create a new group to edit?", style=wx.YES_NO, ) if msg.ShowModal() == wx.ID_YES: self._create_new_group() else: return group_name = self._choice.GetCurrentString() if group_name in self._user_keybinds: catcher = KeyCatcher(self._options, action) catcher.ShowModal() self._user_keybinds[group_name][action] = catcher.key self._rebuild_buttons() def _on_group_change(self, evt): self._rebuild_buttons() @property def options(self) -> Tuple[KeybindContainer, KeybindGroupIdType, KeybindGroup]: keybind_group = self._choice.GetCurrentString() if keybind_group in self._fixed_keybinds: keybinds = self._fixed_keybinds[keybind_group] else: keybinds = self._user_keybinds[keybind_group] return self._user_keybinds, keybind_group, keybinds
Amulet-Map-Editor
amulet_map_editor\api\wx\util\mouse_movement.py
import wx from typing import Tuple from .window_container import WindowContainer class MouseMovement(WindowContainer): """A class to get and set the cursor position and track changes.""" def __init__(self, window: wx.Window): super().__init__(window) # the current mouse position self._x: float = 0 self._y: float = 0 # the resting position of the mouse from which to calculate the delta # if the mouse is warped this will become the warped point self._start_x: float = 0 self._start_y: float = 0 # the sum of all the deltas since it was last reset. # when the mouse is warped the delta before it was warped will be added to this value self._delta_x: float = 0 self._delta_y: float = 0 def bind_events(self): """Set up all events required to run.""" self.window.Bind(wx.EVT_MOTION, self._on_mouse_motion) def _to_relative(self, x: int, y: int) -> Tuple[float, float]: """Convert the x and y values to relative values 0 to 1""" dx, dy = self.window.GetSize() dx = max(1, dx) dy = max(1, dy) return x / dx, y / dy def _to_absolute(self, x: float, y: float) -> Tuple[int, int]: """Convert the relative values to absolute values.""" dx, dy = self.window.GetSize() return int(x * dx), int(y * dy) def _on_mouse_motion(self, evt): """Event fired when the mouse is moved.""" self._x, self._y = self._to_relative(*evt.GetPosition()) evt.Skip() def _screen_middle(self) -> Tuple[int, int]: """Get the pixel coordinate of the middle of the screen""" x, y = self.window.GetSize() return (int(x / 2), int(y / 2)) def warp_middle(self): """Warp the cursor to the middle of the screen.""" self.xy = self._screen_middle() def set_middle(self): """Set the start point to the middle of the screen. Does not warp.""" self._start_x, self._start_y = 0.5, 0.5 def _warp(self): self.window.WarpPointer(*self._to_absolute(self._x, self._y)) @property def x(self) -> int: """The x pixel location of the mouse in the parent window.""" return self._to_absolute(self._x, 0)[0] @x.setter def x(self, x: int): """Set the x pixel location of the mouse in the parent window. Will warp the cursor to this position and create a mouse move event.""" self._delta_x += self._x - self._start_x self._start_x = self._x = self._to_relative(int(x), 0)[0] self._warp() @property def y(self) -> int: """The y pixel location of the mouse in the parent window.""" return self._to_absolute(0, self._y)[1] @y.setter def y(self, y: int): """Set the y pixel location of the mouse in the parent window. Will warp the cursor to this position and create a mouse move event.""" self._delta_y += self._y - self._start_y self._start_y = self._y = self._to_relative(0, int(y))[1] self._warp() @property def xy(self) -> Tuple[int, int]: """The x and y pixel location of the mouse in the parent window.""" return self._to_absolute(self._x, self._y) @xy.setter def xy(self, xy: Tuple[int, int]): """Set the x and y pixel location of the mouse in the parent window. Will warp the cursor to this position and create a mouse move event.""" assert len(xy) == 2, "xy must be an iterable of two ints" x, y = map(int, xy) self._delta_x += self._x - self._start_x self._delta_y += self._y - self._start_y (self._start_x, self._start_y) = (self._x, self._y) = self._to_relative(x, y) self._warp() def reset_delta(self): """Reset the mouse delta values. The amount the mouse has moved will be reset and the start position will become the current position. :return: """ self._delta_x = self._delta_y = 0 self._start_x = self._x self._start_y = self._y @property def delta_x(self) -> int: """The x pixel distance between the current location and the location when reset_delta was called. If the pointer was warped the offset before it was warped will be added to this. """ return self.delta_xy[0] @property def delta_y(self) -> int: """The y pixel distance between the current location and the location when reset_delta was called. If the pointer was warped the offset before it was warped will be added to this. """ return self.delta_xy[1] @property def delta_xy(self) -> Tuple[int, int]: """The x and y pixel distance between the current location and the location when reset_delta was called. If the pointer was warped the offset before it was warped will be added to this. """ return self._to_absolute( self._x - self._start_x + self._delta_x, self._y - self._start_y + self._delta_y, )
Amulet-Map-Editor
amulet_map_editor\api\wx\util\ui_preferences.py
from __future__ import annotations from typing import Type, Tuple, TypedDict, Dict import atexit import wx from amulet_map_editor import CONFIG class WindowConfig(TypedDict): size: Tuple[int, int] position: Tuple[int, int] is_full_screen: bool PRE_EXISTING_CONFIG: Dict[str, WindowConfig] = CONFIG.get("window_preferences", {}) def write_config(): CONFIG.put("window_preferences", PRE_EXISTING_CONFIG) atexit.register(write_config) def preserve_ui_preferences(cls: Type[wx.TopLevelWindow]): assert issubclass( cls, wx.TopLevelWindow ), "This takes a subclass of a top level window." qualified_name = ".".join((cls.__module__, cls.__qualname__)) class TopLevelWindowWrapper(cls): __resized: bool __size: Tuple[int, int] __position: Tuple[int, int] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__resized = False self.__position = self.GetPosition().Get() self.__size = self.GetSize().Get() if qualified_name in PRE_EXISTING_CONFIG: window_config = PRE_EXISTING_CONFIG[qualified_name] x, y = window_config["position"] dx, dy = window_config["size"] # Check if the window header intersects on a connected display. display_count = wx.Display.GetCount() for i in range(display_count): display = wx.Display(i) geometry = display.GetGeometry() if geometry.Intersects(wx.Rect(x, y, dx, 10)): break else: if display_count: # If there is no display at that point move it to the first display. display = wx.Display(0) geometry = display.GetGeometry() x = geometry.x y = geometry.y self.SetPosition(wx.Point(x, y)) self.SetSize(wx.Size(dx, dy)) self.Maximize(window_config.get("is_full_screen", False)) else: self.Maximize() self.Layout() self.Refresh() self.Bind(wx.EVT_MOVE, self.__on_resize) self.Bind(wx.EVT_SIZE, self.__on_resize) self.Bind(wx.EVT_IDLE, self.__on_idle) def __on_idle(self, evt): if self.__resized: self.__resized = False PRE_EXISTING_CONFIG[qualified_name] = { "size": self.__size, "position": self.__position, "is_full_screen": self.IsMaximized(), } evt.Skip() def __on_resize(self, evt): self.__resized = True if not self.IsMaximized(): # only store the non-maximised state self.__position = self.GetPosition().Get() self.__size = self.GetSize().Get() evt.Skip() return TopLevelWindowWrapper
Amulet-Map-Editor
amulet_map_editor\api\wx\util\validators.py
import wx SpecialChrs = { wx.WXK_BACK, wx.WXK_DELETE, wx.WXK_SHIFT, wx.WXK_END, wx.WXK_HOME, wx.WXK_LEFT, wx.WXK_RIGHT, wx.WXK_RETURN, *range(1, 27), } class BaseValidator(wx.Validator): """Validates data as it is entered into the text controls.""" def __init__(self): super().__init__() self.Bind(wx.EVT_CHAR, self.OnChar) def Clone(self): return self.__class__() def Validate(self, win): return True def TransferToWindow(self): return True def TransferFromWindow(self): return True def OnChar(self, event): event.Skip() class IntValidator(BaseValidator): def OnChar(self, event: wx.KeyEvent): keycode = int(event.GetKeyCode()) if ( keycode in SpecialChrs or event.ControlDown() or 48 <= keycode <= 57 or keycode == 45 ): event.Skip() class FloatValidator(BaseValidator): def OnChar(self, event): keycode = int(event.GetKeyCode()) if keycode in SpecialChrs or 45 <= keycode <= 57: event.Skip()
Amulet-Map-Editor
amulet_map_editor\api\wx\util\window_container.py
import weakref import wx class WindowContainer: """A helper class to store a reference to a wx.Window. If a window is hard referenced there may be cyclic references leading to memory leaks. Subclass this class if you intend to store a reference to a window.""" def __init__(self, window: wx.Window): self._window = weakref.ref(window) @property def window(self) -> wx.Window: return self._window()
Amulet-Map-Editor
amulet_map_editor\api\wx\util\__init__.py
Amulet-Map-Editor
amulet_map_editor\api\wx\ui\biome_select\biome_define.py
from typing import Tuple import PyMCTranslate import wx from amulet_map_editor.api.wx.ui.base_define import BaseDefine from amulet_map_editor.api.wx.ui.biome_select.biome_select import BiomeSelect class BiomeDefine(BaseDefine): def __init__( self, parent, translation_manager: PyMCTranslate.TranslationManager, orientation=wx.VERTICAL, platform: str = None, version_number: Tuple[int, int, int] = None, namespace: str = None, biome_name: str = None, show_pick_biome: bool = False, **kwargs, ): super().__init__( parent, translation_manager, BiomeSelect, orientation, platform, version_number, namespace, default_name=biome_name, show_pick=show_pick_biome, show_force_blockstate=False, **kwargs, ) def _on_picker_change(self, evt): evt.Skip() @property def biome_name(self) -> str: return self._picker.name @biome_name.setter def biome_name(self, biome_name: str): self._picker.name = biome_name @property def biome(self) -> str: return f"{self.namespace}:{self.biome_name}" @biome.setter def biome(self, biome: str): namespace, biome_name = biome.split(":") self._picker.set_namespace(namespace) self._picker.set_name(biome_name) @property def universal_biome(self) -> str: return self._translation_manager.get_version( self.platform, self.version_number ).biome.to_universal(self.biome) @universal_biome.setter def universal_biome(self, universal_biome: str): self.biome = self._translation_manager.get_version( self.platform, self.version_number ).biome.from_universal(universal_biome)
Amulet-Map-Editor
amulet_map_editor\api\wx\ui\biome_select\biome_select.py
from amulet_map_editor.api.wx.ui.base_select import BaseSelect class BiomeSelect(BaseSelect): TypeName = "Biome" def _populate_namespace(self): version = self._translation_manager.get_version( self._platform, self._version_number ) namespaces = list( set( [biome_id[: biome_id.find(":")] for biome_id in version.biome.biome_ids] ) ) self._do_text_event = False self._namespace_combo.Set(namespaces) def _populate_item_name(self): version = self._translation_manager.get_version( self._platform, self._version_number ) self._names = [ biome_id[len(self.namespace) + 1 :] for biome_id in version.biome.biome_ids if biome_id.startswith(self.namespace) ] self._list_box.SetItems(self._names)
Amulet-Map-Editor
amulet_map_editor\api\wx\ui\biome_select\__init__.py
from .biome_define import BiomeDefine
Amulet-Map-Editor
amulet_map_editor\api\wx\ui\block_select\block_define.py
import wx import wx.lib.scrolledpanel from typing import Tuple, Optional, Dict, Mapping, Union import PyMCTranslate from amulet.api.block import PropertyType, Block, PropertyValueType from amulet.api.block_entity import BlockEntity from amulet_nbt import SNBTType, AbstractBaseTag from amulet_map_editor.api.wx.ui.base_define import BaseDefine from amulet_map_editor.api.wx.ui.block_select import BlockSelect from amulet_map_editor.api.wx.ui.block_select.properties import ( PropertySelect, WildcardSNBTType, EVT_PROPERTIES_CHANGE, ) class BlockDefine(BaseDefine): def __init__( self, parent, translation_manager: PyMCTranslate.TranslationManager, orientation=wx.VERTICAL, platform: str = None, version_number: Tuple[int, int, int] = None, force_blockstate: bool = None, namespace: str = None, block_name: str = None, properties: Mapping[str, Union[SNBTType, PropertyValueType]] = None, wildcard_properties=False, show_pick_block: bool = False, **kwargs, ): super().__init__( parent, translation_manager, BlockSelect, orientation, platform, version_number, namespace, default_name=block_name, show_pick=show_pick_block, force_blockstate=force_blockstate, **kwargs, ) right_sizer = wx.BoxSizer(wx.VERTICAL) if orientation == wx.HORIZONTAL: self._sizer.Add(right_sizer, 1, wx.EXPAND | wx.LEFT, 5) else: self._sizer.Add(right_sizer, 1, wx.EXPAND | wx.TOP, 5) self._property_picker = PropertySelect( self, translation_manager, self._version_picker.platform, self._version_picker.version_number, self._version_picker.force_blockstate, self._picker.namespace, self._picker.name, { key: val.to_snbt() if isinstance(val, AbstractBaseTag) else val for key, val in (properties or {}).items() }, wildcard_properties, ) right_sizer.Add(self._property_picker, 1, wx.EXPAND) self._property_picker.Bind(EVT_PROPERTIES_CHANGE, self._on_property_change) self.SetSizerAndFit(self._sizer) self.Layout() def _on_picker_change(self, evt): self._update_properties() evt.Skip() def _on_property_change(self, evt): self.Layout() evt.Skip() def _update_properties(self): self._property_picker.version_block = ( self._version_picker.platform, self._version_picker.version_number, self._version_picker.force_blockstate, self._picker.namespace, self._picker.name, ) @property def force_blockstate(self) -> bool: return self._version_picker.force_blockstate @force_blockstate.setter def force_blockstate(self, force_blockstate: bool): self._version_picker.force_blockstate = force_blockstate @property def block_name(self) -> str: return self._picker.name @block_name.setter def block_name(self, block_name: str): self._picker.name = block_name @property def str_properties(self) -> Dict[str, "WildcardSNBTType"]: return self._property_picker.str_properties @str_properties.setter def str_properties(self, str_properties: Dict[str, "WildcardSNBTType"]): self._property_picker.str_properties = str_properties @property def properties(self) -> PropertyType: return self._property_picker.properties @properties.setter def properties(self, properties: PropertyType): self._property_picker.properties = properties @property def block(self) -> Block: return Block(self.namespace, self.block_name, self.properties) @block.setter def block(self, block: Block): self._picker.set_namespace(block.namespace) self._picker.set_name(block.base_name) self._update_properties() self.properties = block.properties @property def block_entity(self) -> Optional[BlockEntity]: return None # TODO @block_entity.setter def block_entity(self, block_entity: Optional[BlockEntity]): if block_entity is not None: pass # TODO @property def universal_block(self) -> Tuple[Block, Optional[BlockEntity]]: return self._translation_manager.get_version( self.platform, self.version_number ).block.to_universal(self.block, self.block_entity, self.force_blockstate)[:2] @universal_block.setter def universal_block(self, universal_block: Tuple[Block, Optional[BlockEntity]]): block, block_entity = universal_block v_block, v_block_entity = self._translation_manager.get_version( self.platform, self.version_number ).block.from_universal(block, block_entity, self.force_blockstate)[:2] if isinstance(v_block, Block): self.block = v_block self.block_entity = v_block_entity if __name__ == "__main__": def main(): app = wx.App() translation_manager = PyMCTranslate.new_translation_manager() dialog = wx.Dialog(None, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) sizer = wx.BoxSizer() dialog.SetSizer(sizer) sizer.Add( BlockDefine(dialog, translation_manager, wx.HORIZONTAL), 1, wx.ALL | wx.EXPAND, 5, ) dialog.Show() dialog.Fit() app.MainLoop() main()
Amulet-Map-Editor
amulet_map_editor\api\wx\ui\block_select\block_select.py
import wx from typing import Tuple import PyMCTranslate from amulet_map_editor.api.wx.ui.base_select import BaseSelect class BlockSelect(BaseSelect): TypeName = "Block" def __init__( self, parent: wx.Window, translation_manager: PyMCTranslate.TranslationManager, platform: str, version_number: Tuple[int, int, int], force_blockstate: bool, namespace: str = None, block_name: str = None, show_pick_block: bool = False, ): super().__init__( parent, translation_manager, platform, version_number, force_blockstate, namespace, block_name, show_pick_block, ) def _populate_namespace(self): version = self._translation_manager.get_version( self._platform, self._version_number ) namespaces = version.block.namespaces(self._force_blockstate) self._do_text_event = False self._namespace_combo.Set(namespaces) def _populate_item_name(self): version = self._translation_manager.get_version( self._platform, self._version_number ) self._names = version.block.base_names(self.namespace, self._force_blockstate) self._list_box.SetItems(self._names) if __name__ == "__main__": def main(): app = wx.App() translation_manager = PyMCTranslate.new_translation_manager() dialog = wx.Dialog(None) sizer = wx.BoxSizer() dialog.SetSizer(sizer) sizer.Add(BlockSelect(dialog, translation_manager, "java", (1, 16, 0), False)) dialog.Show() dialog.Fit() app.MainLoop() main()
Amulet-Map-Editor
amulet_map_editor\api\wx\ui\block_select\multi_block_define.py
import wx import wx.lib.scrolledpanel from typing import List import PyMCTranslate from amulet_map_editor.api.image import ( UP_CARET, DOWN_CARET, TRASH, ADD_ICON, MAXIMIZE, MINIMIZE, ) from amulet_map_editor.api.wx.ui.block_select import BlockDefine, EVT_PROPERTIES_CHANGE class MultiBlockDefine(wx.lib.scrolledpanel.ScrolledPanel): def __init__(self, parent, translation_manager, style=0): super().__init__(parent, style=style) self.SetupScrolling() self._translation_manager = translation_manager self._sizer = wx.BoxSizer(wx.VERTICAL) self._add_button = wx.BitmapButton(self, bitmap=ADD_ICON.bitmap(18, 18)) self._sizer.Add(self._add_button, 0, wx.TOP | wx.LEFT | wx.RIGHT | wx.EXPAND, 5) self._block_picker_sizer = wx.BoxSizer(wx.VERTICAL) self._block_picker_sizer.Add( _CollapsibleBlockDefine(self, translation_manager), 0, wx.TOP | wx.EXPAND, 5 ) self._sizer.Add( self._block_picker_sizer, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM, 5 ) self.SetSizerAndFit(self._sizer) self.Layout() self._add_button.Bind(wx.EVT_BUTTON, self._add) self._fix_enabled_buttons() def _add(self, evt): self.Freeze() self.collapse() block_picker = _CollapsibleBlockDefine(self, self._translation_manager) self._block_picker_sizer.Add(block_picker, 1, wx.TOP | wx.EXPAND, 5) self._block_picker_sizer.Layout() self._sizer.Layout() self.Layout() self._fix_enabled_buttons() self.Refresh() self.Thaw() def move_up(self, obj): sizer = self._block_picker_sizer index = [child.Window for child in sizer.GetChildren()].index(obj) sizer.Detach(obj) sizer.Insert(index - 1 if index > 0 else 0, obj, 0, wx.TOP | wx.EXPAND, 5) self._fix_enabled_buttons() self.Layout() def move_down(self, obj): sizer = self._block_picker_sizer length = sizer.ItemCount index = [child.Window for child in sizer.GetChildren()].index(obj) sizer.Detach(obj) sizer.Insert( index + 1 if index < length - 1 else length - 1, obj, 0, wx.TOP | wx.EXPAND, 5, ) self._fix_enabled_buttons() self.Layout() def delete(self, obj): obj.Hide() obj.Destroy() self._fix_enabled_buttons() self.Layout() def collapse(self): for child in self._block_picker_sizer.GetChildren(): child.Window.collapsed = True def _fix_enabled_buttons(self): windows: List[_CollapsibleBlockDefine] = [ child.Window for child in self._block_picker_sizer.GetChildren() ] for window in windows: window.up_button.Enable() window.down_button.Enable() window.delete_button.Enable() if len(windows) >= 1: windows[0].up_button.Disable() windows[-1].down_button.Disable() if len(windows) == 1: windows[0].delete_button.Disable() class _CollapsibleBlockDefine(wx.Panel): def __init__(self, parent: MultiBlockDefine, translation_manager, collapsed=False): super().__init__(parent, style=wx.BORDER_SIMPLE) self.EXPAND = MAXIMIZE.bitmap(18, 18) self.COLLAPSE = MINIMIZE.bitmap(18, 18) self._collapsed = collapsed sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) header_sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(header_sizer, 0, wx.ALL, 5) self.expand_button = wx.BitmapButton(self, bitmap=self.EXPAND) header_sizer.Add(self.expand_button, 0, 5) self.up_button = wx.BitmapButton(self, bitmap=UP_CARET.bitmap(18, 18)) header_sizer.Add(self.up_button, 0, wx.LEFT, 5) self.up_button.Bind(wx.EVT_BUTTON, lambda evt: parent.move_up(self)) self.down_button = wx.BitmapButton(self, bitmap=DOWN_CARET.bitmap(18, 18)) header_sizer.Add(self.down_button, 0, wx.LEFT, 5) self.down_button.Bind(wx.EVT_BUTTON, lambda evt: parent.move_down(self)) self.delete_button = wx.BitmapButton(self, bitmap=TRASH.bitmap(18, 18)) header_sizer.Add(self.delete_button, 0, wx.LEFT, 5) self.delete_button.Bind(wx.EVT_BUTTON, lambda evt: parent.delete(self)) self.block_define = BlockDefine(self, translation_manager, wx.HORIZONTAL) sizer.Add(self.block_define, 1, wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, 5) self.collapsed = collapsed self.block_label = wx.StaticText( self, label=self._gen_block_string(), style=wx.ST_ELLIPSIZE_END | wx.ST_NO_AUTORESIZE, size=(500, -1), ) header_sizer.Add(self.block_label, 1, wx.ALIGN_CENTER_VERTICAL | wx.LEFT, 5) self.expand_button.Bind( wx.EVT_BUTTON, lambda evt: self._toggle_block_expand(parent) ) self.block_define.Bind(EVT_PROPERTIES_CHANGE, self._on_properties_change) @property def collapsed(self) -> bool: return self._collapsed @collapsed.setter def collapsed(self, collapsed: bool): self._collapsed = collapsed if self._collapsed: self.expand_button.SetBitmap(self.EXPAND) self.block_define.Hide() else: self.expand_button.SetBitmap(self.COLLAPSE) self.block_define.Show() self.TopLevelParent.Layout() def _toggle_block_expand(self, parent: MultiBlockDefine): if self.collapsed: parent.collapse() self.collapsed = not self.collapsed def _on_properties_change(self, evt): self.block_label.SetLabel(self._gen_block_string()) self.TopLevelParent.Layout() evt.Skip() def _gen_block_string(self): base = f"{self.block_define.namespace}:{self.block_define.block_name}" properties = ",".join( ( f"{key}={value}" for key, value in self.block_define.str_properties.items() ) ) return f"{base}[{properties}]" if properties else base if __name__ == "__main__": def main(): app = wx.App() translation_manager = PyMCTranslate.new_translation_manager() dialog = wx.Dialog(None, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) sizer = wx.BoxSizer() dialog.SetSizer(sizer) sizer.Add(MultiBlockDefine(dialog, translation_manager), 1, wx.EXPAND) dialog.Show() dialog.Fit() app.MainLoop() main()
Amulet-Map-Editor
amulet_map_editor\api\wx\ui\block_select\properties.py
import wx from wx.lib import newevent from typing import Tuple, Dict, Optional, List, Union import weakref import PyMCTranslate import amulet_nbt from amulet_nbt import SNBTType from amulet.api.block import PropertyDataTypes, PropertyType WildcardSNBTType = Union[SNBTType, str] from amulet_map_editor.api.image import ADD_ICON, SUBTRACT_ICON ( PropertiesChangeEvent, EVT_PROPERTIES_CHANGE, ) = newevent.NewCommandEvent() # the properties changed class PropertySelect(wx.Panel): def __init__( self, parent: wx.Window, translation_manager: PyMCTranslate.TranslationManager, platform: str, version_number: Tuple[int, int, int], force_blockstate: bool, namespace: str, block_name: str, properties: Dict[str, SNBTType] = None, wildcard_mode=False, ): super().__init__(parent, style=wx.BORDER_SIMPLE) self._parent = weakref.ref(parent) sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) self._translation_manager = translation_manager self._platform: Optional[str] = None self._version_number: Optional[Tuple[int, int, int]] = None self._force_blockstate: Optional[bool] = None self._namespace: Optional[str] = None self._block_name: Optional[str] = None self._manual_enabled = False self._simple = SimplePropertySelect(self, translation_manager, wildcard_mode) sizer.Add(self._simple, 1, wx.EXPAND) self._manual = ManualPropertySelect(self, translation_manager) sizer.Add(self._manual, 1, wx.EXPAND) self._wildcard_mode = wildcard_mode self._set_version_block( (platform, version_number, force_blockstate, namespace, block_name) ) self.set_properties(properties) @property def parent(self) -> wx.Window: return self._parent() @property def wildcard_mode(self) -> bool: return self._wildcard_mode @property def version_block(self) -> Tuple[str, Tuple[int, int, int], bool, str, str]: return ( self._platform, self._version_number, self._force_blockstate, self._namespace, self._block_name, ) @version_block.setter def version_block( self, version_block: Tuple[str, Tuple[int, int, int], bool, str, str] ): self._set_version_block(version_block) self.str_properties = None def _set_version_block( self, version_block: Tuple[str, Tuple[int, int, int], bool, str, str] ): version = version_block[:3] assert ( version[0] in self._translation_manager.platforms() and version[1] in self._translation_manager.version_numbers(version[0]) and isinstance(version[2], bool) ), f"{version} is not a valid version" self._platform, self._version_number, self._force_blockstate = version block = version_block[3:5] assert isinstance(block[0], str) and isinstance( block[1], str ), "The block namespace and block name must be strings" self._namespace, self._block_name = block self._set_ui() @property def str_properties(self) -> Dict[str, WildcardSNBTType]: if self._manual_enabled: return self._manual.properties else: return self._simple.properties @str_properties.setter def str_properties(self, properties: Dict[str, WildcardSNBTType]): self.set_properties(properties) wx.PostEvent( self, PropertiesChangeEvent(self.GetId(), properties=self.str_properties) ) @property def properties(self) -> PropertyType: if self.wildcard_mode: raise Exception( "Accessing the properties attribute is invalid in wildcard mode" ) return { key: amulet_nbt.from_snbt(val) for key, val in self.str_properties.items() } @properties.setter def properties(self, properties: PropertyType): self.str_properties = { key: val.to_snbt() for key, val in (properties or {}).items() } def set_properties(self, properties: Dict[str, SNBTType]): properties = properties or {} self.Freeze() if self._manual_enabled: self._manual.properties = properties else: self._simple.properties = properties self.TopLevelParent.Layout() self.Thaw() def _set_ui(self): self.Freeze() translator = self._translation_manager.get_version( self._platform, self._version_number ).block self._manual_enabled = self._block_name not in translator.base_names( self._namespace, self._force_blockstate ) if self._manual_enabled: self._simple.Hide() self._manual.Show() else: self._simple.Show() self._simple.set_specification( translator.get_specification( self._namespace, self._block_name, self._force_blockstate ) ) self._manual.Hide() self.Thaw() class SimplePropertySelect(wx.Panel): def __init__( self, parent: wx.Window, translation_manager: PyMCTranslate.TranslationManager, wildcard_mode, ): super().__init__(parent) sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) self._translation_manager = translation_manager header_sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(header_sizer, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 5) label = wx.StaticText(self, label="Property Name", style=wx.ALIGN_CENTER) header_sizer.Add(label, 1) label = wx.StaticText( self, label="Property Value (SNBT)", style=wx.ALIGN_CENTER ) header_sizer.Add(label, 1, wx.LEFT, 5) self._property_sizer = wx.GridSizer(2, 5, 5) sizer.Add(self._property_sizer, 0, wx.ALL | wx.EXPAND, 5) self._properties: Dict[str, wx.Choice] = {} self._specification: dict = {} self._wildcard_mode = wildcard_mode def set_specification(self, specification: dict): self._specification = specification @property def properties(self) -> Dict[str, SNBTType]: return { name: choice.GetString(choice.GetSelection()) for name, choice in self._properties.items() } @properties.setter def properties(self, properties: Dict[str, SNBTType]): self.Freeze() self._properties.clear() self._property_sizer.Clear(True) spec_properties: Dict[str, List[str]] = self._specification.get( "properties", {} ) spec_defaults = self._specification.get("defaults", {}) for name, choices in spec_properties.items(): label = wx.StaticText(self, label=name) self._property_sizer.Add(label, 0, wx.ALIGN_CENTER) if self._wildcard_mode: choices = ["*"] + choices choice = wx.Choice(self, choices=choices) self._property_sizer.Add(choice, 0, wx.EXPAND) choice.Bind( wx.EVT_CHOICE, lambda evt: wx.PostEvent( self, PropertiesChangeEvent(self.GetId(), properties=self.properties), ), ) val = spec_defaults[name] if name in properties and val != "*": try: snbt = amulet_nbt.from_snbt(properties[name]).to_snbt() except: pass else: if snbt in choices: val = snbt if val in choices: choice.SetSelection(choices.index(val)) self._properties[name] = choice self.Thaw() self.Fit() self.Layout() class ManualPropertySelect(wx.Panel): def __init__( self, parent: wx.Window, translation_manager: PyMCTranslate.TranslationManager ): super().__init__(parent) sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) self._translation_manager = translation_manager header_sizer = wx.BoxSizer(wx.HORIZONTAL) add_button = wx.BitmapButton( self, bitmap=ADD_ICON.bitmap(30, 30), size=(30, 30) ) header_sizer.Add(add_button) sizer.Add(header_sizer, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 5) label = wx.StaticText(self, label="Property Name", style=wx.ALIGN_CENTER) header_sizer.Add(label, 1, wx.LEFT | wx.ALIGN_CENTER_VERTICAL, 5) label = wx.StaticText( self, label="Property Value (SNBT)", style=wx.ALIGN_CENTER ) header_sizer.Add(label, 1, wx.LEFT | wx.ALIGN_CENTER_VERTICAL, 5) header_sizer.AddStretchSpacer(1) self._property_sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add( self._property_sizer, 0, wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, 5 ) add_button.Bind(wx.EVT_BUTTON, lambda evt: self._add_property()) self._property_index = 0 self._properties: Dict[int, Tuple[wx.TextCtrl, wx.TextCtrl]] = {} def _post_property_change(self): wx.PostEvent( self, PropertiesChangeEvent(self.GetId(), properties=self.properties) ) def _add_property(self, name: str = "", value: SNBTType = ""): self.Freeze() sizer = wx.BoxSizer(wx.HORIZONTAL) self._property_index += 1 subtract_button = wx.BitmapButton( self, bitmap=SUBTRACT_ICON.bitmap(30, 30), size=(30, 30) ) sizer.Add(subtract_button, 0, wx.ALIGN_CENTER_VERTICAL) index = self._property_index subtract_button.Bind( wx.EVT_BUTTON, lambda evt: self._on_remove_property(sizer, index) ) name_entry = wx.TextCtrl(self, value=name, style=wx.TE_CENTER) sizer.Add(name_entry, 1, wx.ALIGN_CENTER_VERTICAL | wx.LEFT, 5) name_entry.Bind(wx.EVT_TEXT, lambda evt: self._post_property_change()) value_entry = wx.TextCtrl(self, value=value, style=wx.TE_CENTER) sizer.Add(value_entry, 1, wx.ALIGN_CENTER_VERTICAL | wx.LEFT, 5) snbt_text = wx.StaticText(self, style=wx.ALIGN_CENTER) sizer.Add(snbt_text, 1, wx.ALIGN_CENTER_VERTICAL | wx.LEFT, 5) self._change_value("", snbt_text) value_entry.Bind(wx.EVT_TEXT, lambda evt: self._on_value_change(evt, snbt_text)) self._property_sizer.Add(sizer, 1, wx.TOP | wx.EXPAND, 5) self._properties[self._property_index] = (name_entry, value_entry) self.Fit() self.TopLevelParent.Layout() self.Thaw() def _on_value_change(self, evt, snbt_text: wx.StaticText): self._change_value(evt.GetString(), snbt_text) self._post_property_change() evt.Skip() def _change_value(self, snbt: SNBTType, snbt_text: wx.StaticText): try: nbt = amulet_nbt.from_snbt(snbt) except: snbt_text.SetLabel("Invalid SNBT") snbt_text.SetBackgroundColour((255, 200, 200)) else: if isinstance(nbt, PropertyDataTypes): snbt_text.SetLabel(nbt.to_snbt()) snbt_text.SetBackgroundColour(wx.NullColour) else: snbt_text.SetLabel(f"{nbt.__class__.__name__} not valid") snbt_text.SetBackgroundColour((255, 200, 200)) self.Layout() def _on_remove_property(self, sizer: wx.Sizer, key: int): self.Freeze() self._property_sizer.Detach(sizer) sizer.Clear(True) del self._properties[key] self.TopLevelParent.Layout() self.Thaw() self._post_property_change() @property def properties(self) -> Dict[str, SNBTType]: properties = {} for name, value in self._properties.values(): try: nbt = amulet_nbt.from_snbt(value.GetValue()) except: continue if name.GetValue() and isinstance(nbt, PropertyDataTypes): properties[name.GetValue()] = nbt.to_snbt() return properties @properties.setter def properties(self, properties: Dict[str, SNBTType]): self._property_sizer.Clear(True) self._properties.clear() self._property_index = 0 for name, value in properties.items(): self._add_property(name, value) if __name__ == "__main__": def main(): translation_manager = PyMCTranslate.new_translation_manager() app = wx.App() dialog = wx.Dialog(None) sizer = wx.BoxSizer() dialog.SetSizer(sizer) sizer.Add( PropertySelect( dialog, translation_manager, "java", (1, 16, 0), False, "minecraft", "oak_fence", ), 1, wx.ALL, 5, ) dialog.Show() dialog.Fit() app.MainLoop() main()
Amulet-Map-Editor
amulet_map_editor\api\wx\ui\block_select\__init__.py
from .block_select import BlockSelect from .properties import PropertySelect, EVT_PROPERTIES_CHANGE from .block_define import BlockDefine from .multi_block_define import MultiBlockDefine
Amulet-Map-Editor
amulet_map_editor\programs\convert\convert.py
import wx from threading import Thread import webbrowser import logging from typing import TYPE_CHECKING, Optional from amulet import load_format from amulet.api.level import BaseLevel from amulet_map_editor import lang from amulet_map_editor.api.wx.ui.simple import SimplePanel, SimpleScrollablePanel from amulet_map_editor.api.wx.ui.select_world import WorldSelectDialog, WorldUI from amulet_map_editor.api.datatypes import MenuData from amulet_map_editor.api.framework.programs import BaseProgram from amulet_map_editor import close_level if TYPE_CHECKING: from amulet.api.wrapper import WorldFormatWrapper log = logging.getLogger(__name__) class ConvertExtension(SimpleScrollablePanel, BaseProgram): def __init__(self, container, world: BaseLevel): super().__init__(container) self._thread: Optional[Thread] = None self.world = world self._close_world_button = wx.Button( self, wx.ID_ANY, label=lang.get("world.close_world") ) self._close_world_button.Bind(wx.EVT_BUTTON, self._close_world) self.add_object(self._close_world_button, 0, wx.ALL | wx.CENTER) self._input = SimplePanel(self, wx.HORIZONTAL) self.add_object(self._input, 0, wx.ALL | wx.CENTER) self._input.add_object( wx.StaticText( self._input, wx.ID_ANY, lang.get("program_convert.input_world"), wx.DefaultPosition, wx.DefaultSize, 0, ), 0, wx.ALL | wx.CENTER, ) self._input.add_object( WorldUI(self._input, self.world.level_wrapper), 0, wx.ALL | wx.CENTER ) self._output = SimplePanel(self, wx.HORIZONTAL) self.add_object(self._output, 0, wx.ALL | wx.CENTER) self._output.add_object( wx.StaticText( self._output, wx.ID_ANY, lang.get("program_convert.output_world"), wx.DefaultPosition, wx.DefaultSize, 0, ), 0, wx.ALL | wx.CENTER, ) self._select_output_button = wx.Button( self, wx.ID_ANY, label=lang.get("program_convert.select_output_world") ) self._select_output_button.Bind(wx.EVT_BUTTON, self._show_world_select) self.add_object(self._select_output_button, 0, wx.ALL | wx.CENTER) self._convert_bar = SimplePanel(self, wx.HORIZONTAL) self.add_object(self._convert_bar, 0, wx.ALL | wx.CENTER) self.loading_bar = wx.Gauge( self._convert_bar, wx.ID_ANY, 100, wx.DefaultPosition, wx.DefaultSize, wx.GA_HORIZONTAL, ) self._convert_bar.add_object(self.loading_bar, options=wx.ALL | wx.EXPAND) self.loading_bar.SetValue(0) self.convert_button = wx.Button( self._convert_bar, wx.ID_ANY, label=lang.get("program_convert.convert_button"), ) self._convert_bar.add_object(self.convert_button) self.convert_button.Bind(wx.EVT_BUTTON, self._convert_event) self.out_world_path = None def menu(self, menu: MenuData) -> MenuData: menu.setdefault(lang.get("menu_bar.help.menu_name"), {}).setdefault( "control", {} ).setdefault( lang.get("program_convert.menu_bar.help.user_guide"), lambda evt: self._help_controls(), ) return menu def _help_controls(self): webbrowser.open( "https://github.com/Amulet-Team/Amulet-Map-Editor/blob/master/amulet_map_editor/programs/convert/readme.md" ) def _show_world_select(self, evt): select_world = WorldSelectDialog(self, self._output_world_callback) select_world.ShowModal() select_world.Destroy() def _output_world_callback(self, path): if path == self.world.level_path: wx.MessageBox(lang.get("program_convert.input_output_must_different")) return try: out_world_format = load_format(path) self.out_world_path = path except Exception: return for child in list(self._output.GetChildren())[1:]: child.Destroy() self._output.add_object(WorldUI(self._output, out_world_format), 0) self._output.Layout() self._output.Fit() self.Layout() # self.Fit() def _update_loading_bar(self, chunk_index, chunk_total): wx.CallAfter(self.loading_bar.SetValue, int(100 * chunk_index / chunk_total)) def _convert_event(self, evt): if self.out_world_path is None: wx.MessageBox(lang.get("program_convert.select_before_converting")) return self.convert_button.Disable() self._thread = Thread(target=self._convert_method) self._thread.start() def _convert_method(self): try: out_world = load_format(self.out_world_path) log.info(f"Converting world {self.world.level_path} to {out_world.path}") out_world: WorldFormatWrapper out_world.open() self.world.save(out_world, self._update_loading_bar) out_world.close() message = lang.get("program_convert.conversion_completed") log.info( f"Finished converting world {self.world.level_path} to {out_world.path}" ) except Exception as e: message = f"Error during conversion\n{e}" log.error(message, exc_info=True) self._update_loading_bar(0, 100) self._thread = None self.convert_button.Enable() wx.MessageBox(message) def can_close(self): if self._thread is not None: log.info( f"World {self.world.level_path} is still being converted. Please let it finish before closing" ) return False return True def _close_world(self, evt): close_level(self.world.level_path)
Amulet-Map-Editor
amulet_map_editor\programs\convert\__init__.py
from amulet_map_editor import lang from .convert import ConvertExtension export = {"name": lang.get("program_convert.tab_name"), "ui": ConvertExtension}
Amulet-Map-Editor
amulet_map_editor\programs\edit\edit.py
from typing import TYPE_CHECKING, Optional, Generator import webbrowser import logging from threading import Thread import traceback import wx from amulet.api.data_types import OperationYieldType EDIT_CONFIG_ID = "amulet_edit" from amulet_map_editor import lang from amulet_map_editor.api.framework.programs import BaseProgram from amulet_map_editor.api.datatypes import MenuData from amulet_map_editor.api.wx.util.key_config import KeyConfigDialog from amulet_map_editor.api.wx.ui.traceback_dialog import TracebackDialog from amulet_map_editor.api.wx.ui.simple import SimpleDialog from amulet_map_editor.programs.edit.api.canvas.edit_canvas import EditCanvas from amulet_map_editor.programs.edit.api.key_config import ( DefaultKeybindGroupId, PresetKeybinds, KeybindKeys, ) from amulet_map_editor.api import config if TYPE_CHECKING: from amulet.api.level import World log = logging.getLogger(__name__) class EditExtension(wx.Panel, BaseProgram): # UI elements _sizer: wx.BoxSizer # these only exists on setup. Once setup is finished they will be None _temp_msg: Optional[wx.StaticText] _temp_loading_bar: Optional[wx.Gauge] _world: "World" _canvas: Optional[EditCanvas] # setup is run in a different thread to avoid blocking the UI _setup_thread: Optional[Thread] def __init__(self, parent, world: "World"): wx.Panel.__init__(self, parent) self._sizer = wx.BoxSizer(wx.VERTICAL) self.SetBackgroundColour( tuple(int(v * 255) for v in EditCanvas.background_colour) ) self.SetSizer(self._sizer) self._world = world self._canvas = None self._setup_thread = None self._sizer.AddStretchSpacer(1) self._temp_msg = wx.StaticText( self, label=lang.get("program_3d_edit.canvas.please_wait") ) self._temp_msg.SetFont(wx.Font(40, wx.DEFAULT, wx.NORMAL, wx.NORMAL)) self._sizer.Add(self._temp_msg, 0, flag=wx.ALIGN_CENTER_HORIZONTAL) self._temp_loading_bar = wx.Gauge(self, range=10000) self._sizer.Add(self._temp_loading_bar, 0, flag=wx.EXPAND) self._sizer.AddStretchSpacer(1) def enable(self): if self._canvas is None: self._canvas = EditCanvas(self, self._world) self._canvas.Hide() self._setup_thread = Thread(target=self._thread_setup) self._setup_thread.start() else: self._canvas.enable() def _update_loading(self, it: Generator[OperationYieldType, None, None]): for arg in it: if isinstance(arg, (int, float)): self._temp_loading_bar.SetValue(int(min(arg, 1) * 10000)) elif ( isinstance(arg, tuple) and isinstance(arg[0], (int, float)) and isinstance(arg[1], str) ): self._temp_loading_bar.SetValue(int(min(arg[0], 1) * 10000)) self._temp_msg.SetLabel(arg[1]) self.Layout() def _display_error(self, msg, tb): dialog = TracebackDialog( self, "Exception while setting up canvas", msg, tb, ) dialog.ShowModal() dialog.Destroy() self.Destroy() def _thread_setup(self): """ Setup and enable all the UI elements. This can take a while to run so should be done in a new thread. Everything in here must be thread safe. """ try: self._update_loading(self._canvas.thread_setup()) except Exception as e: wx.CallAfter(self._display_error, str(e), traceback.format_exc()) raise e else: wx.CallAfter(self._post_thread_setup) def _post_thread_setup(self): """ Run any setup that is not thread safe. """ try: self._update_loading(self._canvas.post_thread_setup()) edit_config: dict = config.get(EDIT_CONFIG_ID, {}) self._canvas.camera.perspective_fov = edit_config.get("options", {}).get( "fov", 70.0 ) if self._canvas.camera.perspective_fov > 180: self._canvas.camera.perspective_fov = 70.0 self._canvas.renderer.render_distance = edit_config.get("options", {}).get( "render_distance", 5 ) self._canvas.camera.rotate_speed = edit_config.get("options", {}).get( "camera_sensitivity", 2.0 ) self._temp_msg = None self._temp_loading_bar = None self._sizer.Clear(True) self._sizer.Add(self._canvas, 1, wx.EXPAND) self._canvas.Show() self._canvas._set_size() self.Layout() wx.CallAfter( self._canvas.enable ) # This must be called after the show handler is run self._setup_thread = None except Exception as e: wx.CallAfter(self._display_error, str(e), traceback.format_exc()) raise e def can_disable(self) -> bool: return self._setup_thread is None def disable(self): if self._canvas is not None: self._canvas.disable() def close(self): """Fully close the UI. Called when destroying the UI.""" if self._canvas is not None: self._canvas.close() def can_close(self) -> bool: """ Check if it is safe to close the UI. :return: True if the program can be closed, False otherwise """ if self._setup_thread is not None: return False elif self._canvas is None: return True elif self._canvas.is_closeable(): return self._check_close_world() else: log.info( f"The canvas in edit for world {self._world.level_wrapper.level_name} was not closeable for some reason." ) return False def _check_close_world(self) -> bool: """ Check if it is safe to close the world and prompt the user if it is not. :return: True if the world can be closed, False otherwise """ unsaved_changes = self._world.history_manager.unsaved_changes if unsaved_changes: msg = wx.MessageDialog( self, f"""There { 'is' if unsaved_changes == 1 else 'are' } {unsaved_changes} unsaved change{ 's' if unsaved_changes >= 2 else '' } in { self._world.level_wrapper.level_name }. Would you like to save?""", style=wx.YES_NO | wx.CANCEL | wx.CANCEL_DEFAULT, ) response = msg.ShowModal() if response == wx.ID_YES: self._canvas.save() return True elif response == wx.ID_NO: return True elif response == wx.ID_CANCEL: log.info( f"""Aborting closing world { self._world.level_wrapper.level_name } because the user pressed cancel.""" ) return False return True def menu(self, menu: MenuData) -> MenuData: menu.setdefault(lang.get("menu_bar.file.menu_name"), {}).setdefault( "system", {} ).setdefault( f"{lang.get('program_3d_edit.menu_bar.file.save')}\tCtrl+s", lambda evt: self._canvas.save(), ) # menu.setdefault(lang.get('menu_bar.file.menu_name'), {}).setdefault('system', {}).setdefault('Save As', lambda evt: self.GetGrandParent().close_world(self.world.world_path)) menu.setdefault( lang.get("program_3d_edit.menu_bar.edit.menu_name"), {} ).setdefault("history", {}).update( { f"{lang.get('program_3d_edit.menu_bar.edit.undo')}\tCtrl+z": lambda evt: self._canvas.undo(), f"{lang.get('program_3d_edit.menu_bar.edit.redo')}\tCtrl+y": lambda evt: self._canvas.redo(), } ) menu.setdefault( lang.get("program_3d_edit.menu_bar.edit.menu_name"), {} ).setdefault("operation", {}).update( { f"{lang.get('program_3d_edit.menu_bar.edit.cut')}\tCtrl+x": lambda evt: self._canvas.cut(), f"{lang.get('program_3d_edit.menu_bar.edit.copy')}\tCtrl+c": lambda evt: self._canvas.copy(), f"{lang.get('program_3d_edit.menu_bar.edit.paste')}\tCtrl+v": lambda evt: self._canvas.paste_from_cache(), f"{lang.get('program_3d_edit.menu_bar.edit.delete')}\tDelete": lambda evt: self._canvas.delete(), } ) menu.setdefault( lang.get("program_3d_edit.menu_bar.edit.menu_name"), {} ).setdefault("shortcut", {}).update( { f"{lang.get('program_3d_edit.menu_bar.edit.goto')}\tCtrl+g": lambda evt: self._canvas.goto(), f"{lang.get('program_3d_edit.menu_bar.edit.select_all')}\tCtrl+A": lambda evt: self._canvas.select_all(), } ) menu.setdefault(lang.get("menu_bar.options.menu_name"), {}).setdefault( "options", {} ).setdefault( lang.get("program_3d_edit.menu_bar.options.controls"), lambda evt: self._edit_controls(), ) menu.setdefault(lang.get("menu_bar.options.menu_name"), {}).setdefault( "options", {} ).setdefault( lang.get("program_3d_edit.menu_bar.options.options"), lambda evt: self._edit_options(), ) menu.setdefault(lang.get("menu_bar.help.menu_name"), {}).setdefault( "help", {} ).setdefault( lang.get("program_3d_edit.menu_bar.help.user_guide"), lambda evt: self._help_controls(), ) return menu def _edit_controls(self): edit_config = config.get(EDIT_CONFIG_ID, {}) keybind_id = edit_config.get("keybind_group", DefaultKeybindGroupId) user_keybinds = edit_config.get("user_keybinds", {}) key_config = KeyConfigDialog( self, keybind_id, KeybindKeys, PresetKeybinds, user_keybinds ) if key_config.ShowModal() == wx.ID_OK: user_keybinds, keybind_id, keybinds = key_config.options edit_config["user_keybinds"] = user_keybinds edit_config["keybind_group"] = keybind_id config.put(EDIT_CONFIG_ID, edit_config) self._canvas.buttons.clear_registered_actions() self._canvas.buttons.register_actions(keybinds) def _edit_options(self): if self._canvas is not None: fov = self._canvas.camera.perspective_fov render_distance = self._canvas.renderer.render_distance camera_sensitivity = self._canvas.camera.rotate_speed dialog = SimpleDialog(self, "Options") sizer = wx.FlexGridSizer(3, 2, 0, 0) dialog.sizer.Add(sizer, flag=wx.ALL, border=5) fov_ui = wx.SpinCtrlDouble(dialog, min=0, max=180, initial=fov) def set_fov(evt): self._canvas.camera.perspective_fov = fov_ui.GetValue() fov_ui.Bind(wx.EVT_SPINCTRLDOUBLE, set_fov) sizer.Add( wx.StaticText(dialog, label="Field of View"), flag=wx.LEFT | wx.TOP | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=5, ) sizer.Add( fov_ui, flag=wx.LEFT | wx.TOP | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=5, ) render_distance_ui = wx.SpinCtrl( dialog, min=0, max=500, initial=render_distance ) def set_render_distance(evt): self._canvas.renderer.render_distance = render_distance_ui.GetValue() render_distance_ui.Bind(wx.EVT_SPINCTRL, set_render_distance) sizer.Add( wx.StaticText(dialog, label="Render Distance"), flag=wx.LEFT | wx.TOP | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=5, ) sizer.Add( render_distance_ui, flag=wx.LEFT | wx.TOP | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=5, ) camera_sensitivity_ui = wx.SpinCtrlDouble( dialog, min=0, max=10, initial=camera_sensitivity ) def set_camera_sensitivity(evt): self._canvas.camera.rotate_speed = camera_sensitivity_ui.GetValue() camera_sensitivity_ui.Bind(wx.EVT_SPINCTRLDOUBLE, set_camera_sensitivity) sizer.Add( wx.StaticText(dialog, label="Camera Sensitivity"), flag=wx.LEFT | wx.TOP | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=5, ) sizer.Add( camera_sensitivity_ui, flag=wx.LEFT | wx.TOP | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=5, ) dialog.Fit() response = dialog.ShowModal() if response == wx.ID_OK: edit_config: dict = config.get(EDIT_CONFIG_ID, {}) edit_config.setdefault("options", {}) edit_config["options"]["fov"] = fov_ui.GetValue() edit_config["options"][ "render_distance" ] = render_distance_ui.GetValue() edit_config["options"][ "camera_sensitivity" ] = camera_sensitivity_ui.GetValue() config.put(EDIT_CONFIG_ID, edit_config) elif response == wx.ID_CANCEL: self._canvas.camera.perspective_fov = fov self._canvas.renderer.render_distance = render_distance self._canvas.camera.rotate_speed = camera_sensitivity @staticmethod def _help_controls(): webbrowser.open( "https://github.com/Amulet-Team/Amulet-Map-Editor/blob/master/amulet_map_editor/programs/edit/readme.md" )
Amulet-Map-Editor
amulet_map_editor\programs\edit\__init__.py
from amulet_map_editor import lang from amulet_map_editor.api.opengl import check_opengl check_opengl() from amulet_map_editor.programs.edit.edit import EditExtension export = {"name": lang.get("program_3d_edit.tab_name"), "ui": EditExtension}
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\chunk_generator.py
import time from typing import Optional from threading import Thread from amulet_map_editor.api.opengl import ThreadedObjectContainer ThreadingEnabled = True if ThreadingEnabled: class ChunkGenerator(ThreadedObjectContainer): def __init__(self): ThreadedObjectContainer.__init__(self) self._enabled = False self._thread: Optional[Thread] = None def start(self): if not self._enabled: if self._thread is not None: raise Exception("Thread being disabled") self._enabled = True self._thread = Thread(target=self._generate_chunks) self._thread.start() def stop(self): if self._enabled: self._enabled = False self._thread.join() self._thread = None def _generate_chunks(self): while self._enabled: self.thread_action() # we need to force the chunk generator to share with the UI code otherwise it eats up all processing time. # TODO: find a better way to do this time.sleep(0.01) else: class ChunkGenerator(ThreadedObjectContainer): def start(self): pass def stop(self): pass
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\edit_canvas_container.py
from typing import TYPE_CHECKING from amulet_map_editor.api.opengl.canvas_container import CanvasContainer if TYPE_CHECKING: from amulet_map_editor.programs.edit.api.canvas import EditCanvas class EditCanvasContainer(CanvasContainer): """A helper class to store a reference to the canvas. This ensures there are no memory leaks due to circular references.""" def __init__(self, canvas: "EditCanvas"): super().__init__(canvas) @property def canvas(self) -> "EditCanvas": return self._canvas()
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\events.py
import wx from wx.lib import newevent from amulet_map_editor.api.opengl.camera import ( CameraMovedEvent, EVT_CAMERA_MOVED, ProjectionChangedEvent, EVT_PROJECTION_CHANGED, SpeedChangedEvent, EVT_SPEED_CHANGED, ) from amulet_map_editor.api.opengl.events import ( PreDrawEvent, EVT_PRE_DRAW, DrawEvent, EVT_DRAW, PostDrawEvent, EVT_POST_DRAW, ) from amulet_map_editor.api.wx.util.button_input import ( InputPressEvent, InputHeldEvent, InputReleaseEvent, EVT_INPUT_PRESS, EVT_INPUT_HELD, EVT_INPUT_RELEASE, ) from .selection import SelectionChangeEvent, EVT_SELECTION_CHANGE DimensionChangeEvent, EVT_DIMENSION_CHANGE = newevent.NewEvent() # the active tool changed _ToolChangeEventType = wx.NewEventType() EVT_TOOL_CHANGE = wx.PyEventBinder(_ToolChangeEventType) class ToolChangeEvent(wx.PyEvent): """Run when the camera has moved or rotated.""" def __init__(self, tool: str, state=None): wx.PyEvent.__init__(self, eventType=_ToolChangeEventType) self.tool = tool self.state = state UndoEvent, EVT_UNDO = newevent.NewEvent() RedoEvent, EVT_REDO = newevent.NewEvent() CreateUndoEvent, EVT_CREATE_UNDO = newevent.NewEvent() SaveEvent, EVT_SAVE = newevent.NewEvent() EditCloseEvent, EVT_EDIT_CLOSE = newevent.NewEvent()
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\key_config.py
from typing import List from amulet_map_editor.api.wx.util.key_config import ( KeybindContainer, KeybindGroup, KeybindGroupIdType, KeyActionType, Space, Shift, MouseLeft, MouseRight, MouseWheelScrollUp, MouseWheelScrollDown, Control, Alt, Tab, ) ACT_MOVE_UP = "ACT_MOVE_UP" ACT_MOVE_DOWN = "ACT_MOVE_DOWN" ACT_MOVE_FORWARDS = "ACT_MOVE_FORWARDS" ACT_MOVE_BACKWARDS = "ACT_MOVE_BACKWARDS" ACT_MOVE_LEFT = "ACT_MOVE_LEFT" ACT_MOVE_RIGHT = "ACT_MOVE_RIGHT" ACT_BOX_CLICK = "ACT_BOX_CLICK" ACT_BOX_CLICK_ADD = "ACT_BOX_CLICK_ADD" ACT_CHANGE_MOUSE_MODE = "ACT_CHANGE_MOUSE_MODE" ACT_INCR_SPEED = "ACT_INCR_SPEED" ACT_DECR_SPEED = "ACT_DECR_SPEED" ACT_INCR_SELECT_DISTANCE = "ACT_INCR_SELECT_DISTANCE" ACT_DECR_SELECT_DISTANCE = "ACT_DECR_SELECT_DISTANCE" ACT_DESELECT_ALL_BOXES = "ACT_DESELECT_ALL_BOXES" ACT_DELESECT_BOX = "ACT_DELESECT_BOX" ACT_INSPECT_BLOCK = "ACT_INSPECT_BLOCK" ACT_CHANGE_PROJECTION = "ACT_CHANGE_PROJECTION" KeybindKeys: List[KeyActionType] = [ ACT_MOVE_UP, ACT_MOVE_DOWN, ACT_MOVE_FORWARDS, ACT_MOVE_BACKWARDS, ACT_MOVE_LEFT, ACT_MOVE_RIGHT, ACT_BOX_CLICK, ACT_BOX_CLICK_ADD, ACT_CHANGE_MOUSE_MODE, ACT_INCR_SPEED, ACT_DECR_SPEED, ACT_INCR_SELECT_DISTANCE, ACT_DECR_SELECT_DISTANCE, ACT_DESELECT_ALL_BOXES, ACT_DELESECT_BOX, ACT_INSPECT_BLOCK, ACT_CHANGE_PROJECTION, ] PresetKeybinds: KeybindContainer = { "right": { ACT_MOVE_UP: ((), Space), ACT_MOVE_DOWN: ((), Shift), ACT_MOVE_FORWARDS: ((), "W"), ACT_MOVE_BACKWARDS: ((), "S"), ACT_MOVE_LEFT: ((), "A"), ACT_MOVE_RIGHT: ((), "D"), ACT_BOX_CLICK: ((), MouseLeft), ACT_BOX_CLICK_ADD: ((Control,), MouseLeft), ACT_CHANGE_MOUSE_MODE: ((), MouseRight), ACT_INCR_SPEED: ((), MouseWheelScrollUp), ACT_DECR_SPEED: ((), MouseWheelScrollDown), ACT_INCR_SELECT_DISTANCE: ((), "R"), ACT_DECR_SELECT_DISTANCE: ((), "F"), ACT_DESELECT_ALL_BOXES: ((Control, Shift), "D"), ACT_DELESECT_BOX: ((Control,), "D"), ACT_INSPECT_BLOCK: ((), Alt), ACT_CHANGE_PROJECTION: ((), Tab), }, "right_laptop": { ACT_MOVE_UP: ((), Space), ACT_MOVE_DOWN: ((), Shift), ACT_MOVE_FORWARDS: ((), "W"), ACT_MOVE_BACKWARDS: ((), "S"), ACT_MOVE_LEFT: ((), "A"), ACT_MOVE_RIGHT: ((), "D"), ACT_BOX_CLICK: ((), MouseLeft), ACT_BOX_CLICK_ADD: ((Control,), MouseLeft), ACT_CHANGE_MOUSE_MODE: ((), MouseRight), ACT_INCR_SPEED: ((), "."), ACT_DECR_SPEED: ((), ","), ACT_INCR_SELECT_DISTANCE: ((), "R"), ACT_DECR_SELECT_DISTANCE: ((), "F"), ACT_DESELECT_ALL_BOXES: ((Control, Shift), "D"), ACT_DELESECT_BOX: ((Control,), "D"), ACT_INSPECT_BLOCK: ((), Alt), ACT_CHANGE_PROJECTION: ((), Tab), }, "left": { ACT_MOVE_UP: ((), Space), ACT_MOVE_DOWN: ((), ";"), ACT_MOVE_FORWARDS: ((), "I"), ACT_MOVE_BACKWARDS: ((), "K"), ACT_MOVE_LEFT: ((), "J"), ACT_MOVE_RIGHT: ((), "L"), ACT_BOX_CLICK: ((), MouseLeft), ACT_BOX_CLICK_ADD: ((Control,), MouseLeft), ACT_CHANGE_MOUSE_MODE: ((), MouseRight), ACT_INCR_SPEED: ((), MouseWheelScrollUp), ACT_DECR_SPEED: ((), MouseWheelScrollDown), ACT_INCR_SELECT_DISTANCE: ((), "Y"), ACT_DECR_SELECT_DISTANCE: ((), "H"), ACT_DESELECT_ALL_BOXES: ((Control, Shift), "D"), ACT_DELESECT_BOX: ((Control,), "D"), ACT_INSPECT_BLOCK: ((), Alt), ACT_CHANGE_PROJECTION: ((), Tab), }, "left_laptop": { ACT_MOVE_UP: ((), Space), ACT_MOVE_DOWN: ((), ";"), ACT_MOVE_FORWARDS: ((), "I"), ACT_MOVE_BACKWARDS: ((), "K"), ACT_MOVE_LEFT: ((), "J"), ACT_MOVE_RIGHT: ((), "L"), ACT_BOX_CLICK: ((), MouseLeft), ACT_BOX_CLICK_ADD: ((Control,), MouseLeft), ACT_CHANGE_MOUSE_MODE: ((), MouseRight), ACT_INCR_SPEED: ((), "."), ACT_DECR_SPEED: ((), ","), ACT_INCR_SELECT_DISTANCE: ((), "Y"), ACT_DECR_SELECT_DISTANCE: ((), "H"), ACT_DESELECT_ALL_BOXES: ((Control, Shift), "D"), ACT_DELESECT_BOX: ((Control,), "D"), ACT_INSPECT_BLOCK: ((), Alt), ACT_CHANGE_PROJECTION: ((), Tab), }, } DefaultKeybindGroupId: KeybindGroupIdType = "right" DefaultKeys: KeybindGroup = PresetKeybinds[DefaultKeybindGroupId]
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\renderer.py
from typing import TYPE_CHECKING, Optional import wx from OpenGL.GL import ( glClear, GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, ) from amulet.api.data_types import Dimension from amulet_map_editor.api.opengl.camera import Projection from amulet_map_editor.api.opengl.mesh.level import RenderLevel from amulet_map_editor.api.opengl.mesh.level_group import LevelGroup from amulet_map_editor.api.opengl.mesh.sky_box import SkyBox from amulet_map_editor.api.opengl.resource_pack.resource_pack import OpenGLResourcePack from .chunk_generator import ThreadingEnabled, ChunkGenerator from .edit_canvas_container import EditCanvasContainer from .events import ( DimensionChangeEvent, CameraMovedEvent, EVT_CAMERA_MOVED, PreDrawEvent, DrawEvent, PostDrawEvent, ) if TYPE_CHECKING: from amulet_map_editor.programs.edit.api.canvas import EditCanvas class Renderer(EditCanvasContainer): """This class holds the drawable objects and has methods to draw them.""" __slots__ = ( "_render_distance", "_chunk_generator", "_opengl_resource_pack", "_render_world", "_chunk_generator", "_fake_levels", "_sky_box", "_draw_timer", "_gc_timer", ) _sky_box: Optional[SkyBox] _fake_levels: Optional[LevelGroup] def __init__( self, canvas: "EditCanvas", world, context_identifier: str, opengl_resource_pack: OpenGLResourcePack, ): super().__init__(canvas) self._render_distance = 5 self._chunk_generator = ChunkGenerator() self._opengl_resource_pack = opengl_resource_pack self._render_world = RenderLevel( context_identifier, opengl_resource_pack, world, draw_floor=True, draw_ceil=True, ) self._chunk_generator.register(self._render_world) self._fake_levels = None self._sky_box = None self._draw_timer = wx.Timer(self.canvas) self._gc_timer = wx.Timer(self.canvas) def bind_events(self): """Set up all events required to run.""" self.canvas.Bind(wx.EVT_TIMER, self._gc, self._gc_timer) self.canvas.Bind( wx.EVT_TIMER, self._do_draw, self._draw_timer, ) self.canvas.Bind(EVT_CAMERA_MOVED, self._on_camera_moved) self.canvas.Bind(wx.EVT_WINDOW_DESTROY, self._on_destroy, self.canvas) def enable(self): """Enable and start working.""" self.enable_threads() def disable(self): """Disable and unload all geometry.""" self.disable_threads() self.render_world.unload() self.fake_levels.unload() def _on_destroy(self, evt): self.disable() evt.Skip() def is_closeable(self): """Check that the data is safe to be closed.""" return self.render_world.is_closeable() def close(self): """Close and destroy all data.""" self.render_world.close() self.fake_levels.clear() self.sky_box.unload() def disable_threads(self): """Stop the generation of new chunk geometry. Makes it safe to modify the world data.""" self._draw_timer.Stop() self._gc_timer.Stop() self._chunk_generator.stop() def enable_threads(self): """Start the generation of new chunk geometry.""" self.render_world.enable() self.fake_levels.enable() self._chunk_generator.start() self._draw_timer.Start(15) self._gc_timer.Start(10000) # TODO: move this logic into a resource pack reload method # def _load_resource_pack(self, *resource_packs: JavaResourcePack): # self._resource_pack = JavaResourcePackManager(resource_packs) # for _ in self._create_atlas(): # pass @property def opengl_resource_pack(self) -> OpenGLResourcePack: return self._opengl_resource_pack @property def render_world(self) -> RenderLevel: return self._render_world @property def fake_levels(self) -> LevelGroup: """Floating levels that are not the main level.""" if self._fake_levels is None: self._fake_levels: LevelGroup = LevelGroup( self.canvas.context_identifier, self.opengl_resource_pack, ) self._chunk_generator.register(self._fake_levels) return self._fake_levels @property def sky_box(self) -> SkyBox: """The cube in the distance displaying the sky.""" if self._sky_box is None: self._sky_box = SkyBox( self._render_world.context_identifier, self._opengl_resource_pack, ) return self._sky_box @property def dimension(self) -> Dimension: """The currently loaded dimension in the renderer.""" return self.render_world.dimension @dimension.setter def dimension(self, dimension: Dimension): """Set the currently loaded dimension in the renderer.""" if dimension != self.dimension: self.disable_threads() self.render_world.dimension = dimension wx.PostEvent(self.canvas, DimensionChangeEvent(dimension=dimension)) self.enable_threads() @property def render_distance(self) -> int: """The distance from the camera in chunks that should be drawn""" return self._render_distance @render_distance.setter def render_distance(self, render_distance: int): """Set the distance from the camera in chunks that should be drawn""" self._render_distance = render_distance self.render_world.render_distance = render_distance # self.fake_levels.render_distance = render_distance # TODO def _on_camera_moved(self, evt: CameraMovedEvent): """The camera has moved. Update each class's camera state.""" self.move_camera(evt.camera_location, evt.camera_rotation) evt.Skip() def move_camera(self, location, rotation): # TODO: add combined methods self.render_world.camera_location = location self.render_world.camera_rotation = rotation self.fake_levels.set_camera_location(*location) self.fake_levels.set_camera_rotation(*rotation) self.sky_box.set_camera_location(location) def _do_draw(self, evt): wx.PostEvent(self.canvas, PreDrawEvent()) wx.PostEvent(self.canvas, DrawEvent()) wx.PostEvent(self.canvas, PostDrawEvent()) def default_draw(self): """The default draw logic.""" self.start_draw() if self.canvas.camera.projection_mode == Projection.PERSPECTIVE: self.draw_sky_box() glClear(GL_DEPTH_BUFFER_BIT) self.draw_level() self.end_draw() def start_draw(self): """Run commands before drawing.""" glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) def draw_sky_box(self): """Draw the skybox.""" self.sky_box.draw(self.canvas.camera.transformation_matrix) def draw_level(self): """Draw the main level.""" self.render_world.draw(self.canvas.camera.transformation_matrix) def draw_fake_levels(self): """Draw the floating structure levels.""" self.fake_levels.draw(self.canvas.camera.transformation_matrix) if ThreadingEnabled: def end_draw(self): """Run commands after drawing.""" self.canvas.SwapBuffers() else: def end_draw(self): """Run commands after drawing.""" self.canvas.SwapBuffers() self._chunk_generator.thread_action() def _gc(self, event): """Unload data to limit memory usage.""" self.render_world.run_garbage_collector() self.fake_levels.run_garbage_collector() event.Skip()
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\selection.py
from typing import Tuple, Optional, Any, TYPE_CHECKING import logging import wx import weakref from amulet.api.selection import SelectionGroup, SelectionBox from amulet.api.history.history_manager import ObjectHistoryManager from amulet.api.history import Changeable log = logging.getLogger(__name__) if TYPE_CHECKING: from amulet_map_editor.programs.edit.api.canvas import EditCanvas BoxType = Tuple[Tuple[int, int, int], Tuple[int, int, int]] # min and max positions _SelectionChangeEventType = wx.NewEventType() EVT_SELECTION_CHANGE = wx.PyEventBinder(_SelectionChangeEventType) class SelectionChangeEvent(wx.PyEvent): """Run when the selection is changed by third party code.""" def __init__(self): wx.PyEvent.__init__(self, eventType=_SelectionChangeEventType) class SelectionManager(Changeable): """A class containing the raw representation of the selection with methods to access and change it.""" def __init__(self, canvas: "EditCanvas"): super().__init__() self._selection_corners: Tuple[BoxType, ...] = () self._selection_group: SelectionGroup = SelectionGroup() self._canvas = weakref.ref(canvas) self._timer = wx.Timer(canvas) @property def canvas(self) -> "EditCanvas": return self._canvas() def bind_events(self): """Set up all events required to run.""" self.canvas.Bind(wx.EVT_TIMER, self._create_undo_point, self._timer) self.canvas.Bind(wx.EVT_WINDOW_DESTROY, self._on_destroy, self.canvas) def _create_undo_point(self, evt): self.canvas.create_undo_point(False, True) evt.Skip() def _start_undo_point(self): """Start a timer to create an undo point after a period of time. If this is called again before the timer runs then the last call will not happen. """ self._timer.StartOnce(400) def _on_destroy(self, evt): self._timer.Stop() evt.Skip() @property def selection_corners( self, ) -> Tuple[Tuple[Tuple[int, int, int], Tuple[int, int, int]], ...]: """Get the minimum and maximum points of each selection :return: The minimum and maximum points of each selection """ return self._selection_corners @selection_corners.setter def selection_corners( self, selection_corners: Tuple[ Tuple[Tuple[int, int, int], Tuple[int, int, int]], ... ], ): """Set the minimum and maximum points of each selection Will create events that allow the program to update. :param selection_corners: The minimum and maximum points of each selection :return: """ self.set_selection_corners(selection_corners) self._start_undo_point() def set_selection_corners( self, selection_corners: Tuple[ Tuple[Tuple[int, int, int], Tuple[int, int, int]], ... ], ): """Set the minimum and maximum points of each selection Note this method will not trigger the history logic. You may instead want the selection_corners setter method. :param selection_corners: The minimum and maximum points of each selection :return: """ selections = [] for points in selection_corners: if len(points) == 2 and all(len(point) == 3 for point in points): selections.append( tuple(tuple(int(p) for p in point) for point in points) ) else: log.error( f"selection_corners must be of the format Tuple[Tuple[Tuple[int, int, int], Tuple[int, int, int]], ...]" ) self.changed = True self._selection_corners = tuple(selections) self._selection_group = SelectionGroup( [SelectionBox(*box) for box in self._selection_corners] ) wx.PostEvent(self._canvas(), SelectionChangeEvent()) @property def selection_group(self) -> SelectionGroup: """Get the selection as a `SelectionGroup` :return: `SelectionGroup` """ return self._selection_group @selection_group.setter def selection_group(self, selection_group: SelectionGroup): """Set the selection from a `SelectionGroup` class Will create events that allow the program to update. :param selection_group: The `SelectionGroup` to pull the data from :return: """ self.set_selection_group(selection_group) self._start_undo_point() def set_selection_group(self, selection_group: SelectionGroup): """Set the selection from a `SelectionGroup` class Note this method will not trigger the history logic. You may instead want the selection_group setter method. :param selection_group: The `SelectionGroup` to pull the data from :return: """ self.changed = True self._selection_corners = [ (box.min, box.max) for box in selection_group.selection_boxes ] self._selection_group = selection_group wx.PostEvent(self._canvas(), SelectionChangeEvent()) class SelectionHistoryManager(ObjectHistoryManager): def __init__(self, selection_manager: SelectionManager): super().__init__(selection_manager) @property def value(self) -> SelectionManager: return self._value def _unpack_value(self, value: Optional[Any]): self.value.set_selection_corners(value) def _pack_value(self, value: SelectionManager) -> Optional[Any]: return value.selection_corners
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\__init__.py
from .edit_canvas_container import EditCanvasContainer from .canvas import EditCanvas
Amulet-Map-Editor
amulet_map_editor\programs\edit\plugins\__init__.py
Amulet-Map-Editor
amulet_map_editor\programs\edit\amulet_resource_pack\bedrock\manifest.json
{ "format_version": 2, "header": { "description": "Textures for the Amulet renderer", "name": "Textures for the Amulet renderer", "uuid": "a29e7a15-2ea8-4be4-895a-a85866d9b2d3", "version": [0, 0, 1], "min_engine_version": [ 1, 14, 0 ] }, "modules": [ { "description": "Textures for the Amulet renderer", "type": "resources", "uuid": "905f61c8-6f45-4e11-8adb-fe571202aa27", "version": [0, 0, 1] } ] }
Amulet-Map-Editor
amulet_map_editor\programs\edit\amulet_resource_pack\bedrock\textures\terrain_texture.json
{ "num_mip_levels" : 4, "padding" : 8, "resource_pack_name" : "amulet", "texture_data" : { "amulet_selection" : { "textures" : "amulet_ui/selection" }, "amulet_translucent_white" : { "textures" : "amulet_ui/translucent_white" } }, "texture_name" : "atlas.terrain" }
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\behaviour\base_behaviour.py
from typing import TYPE_CHECKING from ..edit_canvas_container import EditCanvasContainer if TYPE_CHECKING: from amulet_map_editor.programs.edit.api.canvas import EditCanvas class BaseBehaviour(EditCanvasContainer): """This class implements how the program actually works. It detects various inputs and sets the state of the program accordingly. This is just a shell of the class to implement the API.""" def __init__(self, canvas: "EditCanvas"): super().__init__(canvas) def bind_events(self): """Set up all events required to run.""" pass
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\behaviour\block_selection_behaviour.py
from typing import TYPE_CHECKING, Tuple, Optional import time import numpy import wx from wx.lib import newevent from ..events import ( InputPressEvent, InputReleaseEvent, EVT_INPUT_RELEASE, EVT_SELECTION_CHANGE, ) from amulet.api.selection import SelectionGroup, SelectionBox from amulet.api.data_types import ( PointCoordinates, BlockCoordinates, ) from amulet_map_editor.api.opengl.camera import Projection from amulet_map_editor.api.opengl.mesh.selection import ( RenderSelectionEditable, RenderSelectionGroupHighlightable, ) from .pointer_behaviour import PointerBehaviour from ..key_config import ( ACT_BOX_CLICK, ACT_BOX_CLICK_ADD, ACT_INCR_SELECT_DISTANCE, ACT_DECR_SELECT_DISTANCE, ACT_DESELECT_ALL_BOXES, ACT_DELESECT_BOX, ) if TYPE_CHECKING: from ..canvas import EditCanvas # the active selection was changed from local code. Not fired by active_block_positions.setter _RenderBoxChangeEvent = wx.NewEventType() EVT_RENDER_BOX_CHANGE = wx.PyEventBinder(_RenderBoxChangeEvent) class RenderBoxChangeEvent(wx.PyEvent): """Run when the selection is changed by third party code.""" def __init__(self, point1: BlockCoordinates, point2: BlockCoordinates): wx.PyEvent.__init__(self, eventType=_RenderBoxChangeEvent) self._point1 = point1 self._point2 = point2 @property def point1(self) -> BlockCoordinates: return self._point1 @property def point2(self) -> BlockCoordinates: return self._point2 @property def points(self) -> Tuple[BlockCoordinates, BlockCoordinates]: return self._point1, self._point2 # run when self._editing is set to True or the active selection is removed. Locks external editing RenderBoxDisableInputsEvent, EVT_RENDER_BOX_DISABLE_INPUTS = newevent.NewEvent() # run when self._editing is set to False and there is an active selection. Allows external editing RenderBoxEnableInputsEvent, EVT_RENDER_BOX_ENABLE_INPUTS = newevent.NewEvent() NPArray2x3 = numpy.ndarray NPVector3 = numpy.ndarray class BlockSelectionBehaviour(PointerBehaviour): """Adds the behaviour for a block based selection.""" def __init__(self, canvas: "EditCanvas"): super().__init__(canvas) self._selection: RenderSelectionGroupHighlightable = ( RenderSelectionGroupHighlightable( self.canvas.context_identifier, self.canvas.renderer.opengl_resource_pack, ) ) self._active_selection: Optional[RenderSelectionEditable] = None self._editing = False # is the active selection being created or resized self._press_time = 0 # the time when the last box edit started self._start_point_1: NPArray2x3 = numpy.zeros( (2, 3) ) # the state of the cursor when editing starts self._start_point_2: NPArray2x3 = numpy.zeros( (2, 3) ) # the state of the cursor when editing starts self._highlight = False # is a box being highlighted self._initial_box: Optional[NPArray2x3] = ( None # the state of the box when editing started ) self._pointer_mask: NPArray2x3 = numpy.zeros((2, 3), dtype=bool) self._resizing = False # is a box being resized self._pointer_distance2 = 0 # the pointer distance used when resizing def _create_active_selection(self): """Create the active selection if it does not exist.""" if self._active_selection is None: self._active_selection = RenderSelectionEditable( self.canvas.context_identifier, self.canvas.renderer.opengl_resource_pack, ) def _unload_active_selection(self): """Unload the active selection if it exists.""" if self._active_selection is not None: self._active_selection.unload() self._active_selection = None def bind_events(self): super().bind_events() self.canvas.Bind(EVT_INPUT_RELEASE, self._on_input_release) self.canvas.Bind(EVT_SELECTION_CHANGE, self._on_selection_change) self.canvas.Bind(wx.EVT_KEY_DOWN, self._on_key_press) def enable(self): self.pull_selection() def _on_selection_change(self, evt): self.pull_selection() evt.Skip() def push_selection(self): """Write the current state to the global selection triggering an undo point.""" self.canvas.selection.selection_group = self.selection_group def pull_selection(self): """Pull the selection from the canvas.""" selection = self.canvas.selection.selection_group self.selection_group = selection if selection: self._enable_inputs() else: self._disable_inputs() def _post_change_event(self): super()._post_change_event() wx.PostEvent(self.canvas, RenderBoxChangeEvent(*self.active_block_positions)) def _disable_inputs(self): wx.PostEvent(self.canvas, RenderBoxDisableInputsEvent()) def _enable_inputs(self): wx.PostEvent(self.canvas, RenderBoxEnableInputsEvent()) def _on_input_press(self, evt: InputPressEvent): if evt.action_id == ACT_INCR_SELECT_DISTANCE: if self._resizing: self._pointer_distance2 += 1 else: self._pointer_distance += 1 self._pointer_moved = True elif evt.action_id == ACT_DECR_SELECT_DISTANCE: if self._resizing: self._pointer_distance2 -= 1 else: self._pointer_distance -= 1 self._pointer_moved = True elif evt.action_id == ACT_BOX_CLICK: if not self._editing: default_create = True self._press_time = time.time() self._disable_inputs() if ACT_BOX_CLICK_ADD in self.canvas.buttons.pressed_actions: # create a new box if self._active_selection is not None: # move the existing active to the inactive self._selection.selection_group = ( self._selection.selection_group + self._active_selection.selection_group ) elif self._highlight: # edit the highlighted box box_index, distance, faces = self._get_box_faces() if box_index is None: # this shouldn't happen but just to be safe. self._selection.selection_group = SelectionGroup() else: if box_index < len(self._selection): # a static selection box is highlighted selection_group = self.selection_group self._selection.selection_group = ( selection_group[:box_index] + selection_group[box_index + 1 :] ) self._active_selection.selection_box = selection_group[ box_index ] self._post_change_event() ( self._start_point_1, self._start_point_2, ) = self._get_active_points() self._pointer_distance2 = distance + 0.01 self._pointer_mask = faces self._active_selection.set_highlight_edges(faces) self._initial_box = self._active_selection.points self._resizing = True default_create = False self._pointer_moved = True else: # clear the selection self._selection.selection_group = SelectionGroup() self._create_active_selection() self._active_selection.locked = False self._editing = True if default_create: self._start_point_1 = self._pointer.bounds self._pointer_mask = numpy.array( [[False] * 3, [True] * 3], dtype=bool ) self._active_selection.set_highlight_edges(self._pointer_mask) self._initial_box = None self._resizing = False elif evt.action_id == ACT_DESELECT_ALL_BOXES: if self.selection_group: self.selection_group = SelectionGroup() self.push_selection() self._disable_inputs() self._post_change_event() else: self._escape() elif evt.action_id == ACT_DELESECT_BOX: if ACT_DESELECT_ALL_BOXES not in self.canvas.buttons.pressed_actions: selection_group = self.selection_group if selection_group: self.selection_group = selection_group[:-1] self.push_selection() if self._active_selection is None: self._disable_inputs() self._post_change_event() else: self._escape() evt.Skip() def _on_key_press(self, evt: wx.KeyEvent): key = evt.GetUnicodeKey() or evt.GetKeyCode() if key == wx.WXK_ESCAPE: self._escape() evt.Skip() def _on_input_release(self, evt: InputReleaseEvent): if evt.action_id == ACT_BOX_CLICK: if self._editing and time.time() - self._press_time > 0.1: self._editing = self._resizing = False self._enable_inputs() self._active_selection.locked = True self.push_selection() evt.Skip() def _escape(self): """Reset the state to how it was before editing.""" if self._editing: if self._initial_box is None: # there was no initial box if self._selection: # static selection exists. Load the last into the active. self._create_active_selection() selection_group = self.selection_group self._selection.selection_group = selection_group[:-1] self._active_selection.selection_box = selection_group[-1] self._active_selection.locked = True self._enable_inputs() else: self._unload_active_selection() else: # there was an initial box self._create_active_selection() self._active_selection.points = self._initial_box self._active_selection.locked = True self._enable_inputs() self._editing = self._resizing = False self._highlight = False self._post_change_event() def _get_active_points(self) -> Tuple[NPArray2x3, NPArray2x3]: """Get the 1x1x1 box coords for the active selection.""" p1, p2 = numpy.zeros((2, 3)), numpy.zeros((2, 3)) if self._active_selection is not None: p1[0], p2[0] = self._active_selection.points p1[1] = p1[0] + 1 p2[1] = p2[0] + 1 mult = p1[0] < p2[0] p1 -= 1 * numpy.logical_not(mult) p2 -= 1 * mult return p1, p2 @property def active_block_positions( self, ) -> Tuple[Tuple[int, int, int], Tuple[int, int, int]]: """Get the active box positions. The coordinates for the maximum point of the box will be one less because this is the block position. """ if self._active_selection is None: return (0, 0, 0), (0, 0, 0) else: p1, p2 = self._get_active_points() return tuple(p1[0].tolist()), tuple(p2[0].tolist()) @active_block_positions.setter def active_block_positions( self, positions: Tuple[Tuple[int, int, int], Tuple[int, int, int]] ): """Set the active box positions. This should only be used when not editing. The coordinates for the maximum point of the box will be one greater because this is the block position. """ if self._active_selection is not None and not self._editing: self._pointer_mask[:] = False self._start_point_1[:] = positions[0] self._start_point_2[:] = positions[1] self._start_point_1[1] += 1 self._start_point_2[1] += 1 ( self._active_selection.point1, self._active_selection.point2, ) = self._get_editing_selection() self.push_selection() else: self._disable_inputs() @property def selection_group(self) -> SelectionGroup: """The selection group of the static and active selection. If the active selection is being resized it will not be included in this.""" selection_group = self._selection.selection_group if self._active_selection is not None and not self._editing: selection_group += self._active_selection.selection_group return selection_group @selection_group.setter def selection_group(self, selection_group: SelectionGroup): """Set the selection group of the static and active selection. This will only trigger a grapical change and will not update the global selection. A call to push_selection is required to push the updated selection to the global selection. """ self._escape() if len(selection_group) == 0: # unload the active selection if self._active_selection is not None: self._unload_active_selection() if len(selection_group) <= 1: # unload the selection group self._selection.selection_group = SelectionGroup() if len(selection_group) >= 1: # load the active selection self._create_active_selection() self._active_selection.selection_box = selection_group[-1] if len(selection_group) >= 2: # load the selection group self._selection.selection_group = selection_group[:-1] def _get_editing_selection(self) -> Tuple[NPVector3, NPVector3]: """Get the minimum and maximum points of the editing selection. This is based on the stored starting pointer and the current pointer.""" start_point_1 = self._start_point_1.copy() start_point_2 = self._start_point_2.copy() pointer = self._pointer.bounds.copy() start_point_1[:, self._pointer_mask[0]] = pointer[:, self._pointer_mask[0]] start_point_2[:, self._pointer_mask[1]] = pointer[:, self._pointer_mask[1]] start_1, start_2 = start_point_1 point_1, point_2 = start_point_2 start = start_1 point = point_1 mask = numpy.abs(start - point_1) < numpy.abs(start - point_2) point[mask] = point_2[mask] mask = numpy.abs(point - start_1) < numpy.abs(point - start_2) start[mask] = start_2[mask] return start, point def _update_pointer(self): # find the closest box position # check if there are any blocks up to that position # find the closest box position # find the closest box or block position if self._pointer_moved: if self.canvas.camera.projection_mode == Projection.TOP_DOWN: camera = self.canvas.camera.location camera = (camera[0], 10**9, camera[2]) look_vector = self.look_vector() selection_group, box_index, max_distance = self._get_box_hit_data( camera, look_vector ) location, hit_block = self.closest_block_2d( int(10**9 - min(max_distance, 10**9)) + 1 ) else: ( camera, look_vector, selection_group, box_index, max_distance, ) = self._get_default_box_hit_data() if self.canvas.camera.rotating: if self._resizing: location = self.distance_block_3d(self._pointer_distance2) else: location = self.distance_block_3d(self._pointer_distance) hit_block = True else: if self._resizing: location = self.distance_block_3d(self._pointer_distance2) hit_block = True else: location, hit_block = self.closest_block_3d( min(max_distance, 100) ) self._pointer.point1, self._pointer.point2 = location, location + 1 self._pointer_moved = False if self._editing: ( self._active_selection.point1, self._active_selection.point2, ) = self._get_editing_selection() self._post_change_event() else: self._selection.reset_highlight_edges() if box_index is None or hit_block: # if no box was hit or a block was hit self._highlight = False if self._active_selection is not None: self._active_selection.reset_highlight_edges() else: self._highlight = True faces_hit = self._get_box_faces_manual( camera, look_vector, selection_group, box_index, max_distance ) location = numpy.floor( camera + look_vector * (max_distance + 0.01) ).astype(int) self._pointer.point1, self._pointer.point2 = location, location + 1 if box_index == len(self._selection): self._active_selection.set_highlight_edges(faces_hit) else: self._selection.set_highlight_edges(box_index, faces_hit) self._active_selection.reset_highlight_edges() def _get_default_box_hit_data( self, ) -> Tuple[PointCoordinates, NPVector3, SelectionGroup, Optional[int], float]: camera = self.canvas.camera.location look_vector = self.look_vector() return (camera, look_vector) + self._get_box_hit_data(camera, look_vector) def _get_box_hit_data( self, camera: PointCoordinates, look_vector: NPVector3 ) -> Tuple[SelectionGroup, Optional[int], float]: selection_group = self.selection_group box_index, max_distance = selection_group.closest_vector_intersection( camera, look_vector ) return selection_group, box_index, max_distance def _get_box_faces(self) -> Tuple[Optional[int], float, NPArray2x3]: """Get collision information between a vector and a selection group. If the vector intersects a box in the selection group it will return The index of the selection box in the selection group. A 2x3 bool array of the faces that were hit as corresponding to point1 and point2 x,y,z If the vector does not hit the selection the same structure applies but will look like this None 2x3 False array""" ( camera, look_vector, selection_group, box_index, max_distance, ) = self._get_default_box_hit_data() return ( box_index, max_distance, self._get_box_faces_manual( camera, look_vector, selection_group, box_index, max_distance ), ) @staticmethod def _get_box_faces_manual( camera: PointCoordinates, look_vector: NPVector3, selection_group: SelectionGroup, box_index: Optional[int], max_distance: float, ) -> NPArray2x3: """Get a 2x3 bool array of the faces the look vector first contacts. point1 (x y z), point2 (x y z)""" if box_index is None: # it doesn't hit any boxes return numpy.zeros((2, 3), dtype=bool) else: box: SelectionBox = selection_group[box_index] point = max_distance * look_vector + camera tol = numpy.min([numpy.array(box.shape) / 4, numpy.ones(3)], 0) return numpy.abs(box.points_array - point) < tol def draw(self): if self.canvas.camera.projection_mode == Projection.TOP_DOWN: camera = None else: camera = self.canvas.camera.location self._selection.draw(self.canvas.camera.transformation_matrix, camera) if self._active_selection is not None: self._active_selection.draw( self.canvas.camera.transformation_matrix, camera ) if not self._highlight and not self._editing: super().draw()
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\behaviour\camera_behaviour.py
from typing import TYPE_CHECKING import math import wx import time from amulet_map_editor.api.opengl.camera import Projection from amulet_map_editor.api.opengl.data_types import CameraRotationType from .base_behaviour import BaseBehaviour from ..events import ( InputHeldEvent, EVT_INPUT_HELD, InputPressEvent, EVT_INPUT_PRESS, InputReleaseEvent, EVT_INPUT_RELEASE, ) from ..key_config import ( ACT_MOVE_UP, ACT_MOVE_DOWN, ACT_MOVE_FORWARDS, ACT_MOVE_BACKWARDS, ACT_MOVE_LEFT, ACT_MOVE_RIGHT, ACT_CHANGE_MOUSE_MODE, ACT_INCR_SPEED, ACT_DECR_SPEED, ACT_CHANGE_PROJECTION, ) if TYPE_CHECKING: from amulet_map_editor.programs.edit.api.canvas import EditCanvas class CameraBehaviour(BaseBehaviour): """Adds the normal behaviour for the camera.""" def __init__(self, canvas: "EditCanvas"): super().__init__(canvas) self._previous_mouse_lock = self.canvas.camera.rotating = False self._toggle_mouse_time = 0 self._last_camera_rotation: CameraRotationType = (0.0, 0.0) def bind_events(self): """Set up all events required to run.""" self.canvas.Bind(EVT_INPUT_HELD, self._on_input_held) self.canvas.Bind(EVT_INPUT_PRESS, self._on_input_press) self.canvas.Bind(EVT_INPUT_RELEASE, self._on_input_release) self.canvas.Bind(wx.EVT_KEY_DOWN, self._on_key_press) self.canvas.Bind(wx.EVT_KILL_FOCUS, self._on_loss_focus) self.canvas.Bind(wx.EVT_MOTION, self._on_mouse_motion) def _on_mouse_motion(self, evt): self.canvas.SetFocus() evt.Skip() def _on_key_press(self, evt: wx.KeyEvent): key = evt.GetUnicodeKey() or evt.GetKeyCode() if key == wx.WXK_ESCAPE: self._escape() evt.Skip() def _on_input_press(self, evt: InputPressEvent): """Logic to run each time the input press event is run.""" if evt.action_id == ACT_CHANGE_PROJECTION: if self.canvas.camera.projection_mode == Projection.PERSPECTIVE: self._last_camera_rotation = self.canvas.camera.rotation self.canvas.camera.rotation = 180, 90 self.canvas.camera.projection_mode = Projection.TOP_DOWN elif self.canvas.camera.projection_mode == Projection.TOP_DOWN: self.canvas.camera.rotation = self._last_camera_rotation self.canvas.camera.projection_mode = Projection.PERSPECTIVE elif evt.action_id == ACT_CHANGE_MOUSE_MODE: self.canvas.SetFocus() self._previous_mouse_lock = self.canvas.camera.rotating self._capture_mouse() self._toggle_mouse_time = time.time() def _on_input_release(self, evt: InputReleaseEvent): """Logic to run each time the input release event is run.""" if evt.action_id == ACT_CHANGE_MOUSE_MODE: if self._previous_mouse_lock or time.time() - self._toggle_mouse_time > 0.1: self._release_mouse() else: self._capture_mouse() elif evt.action_id == ACT_INCR_SPEED: if self.canvas.camera.projection_mode == Projection.PERSPECTIVE: self.canvas.camera.move_speed *= 1.1 elif self.canvas.camera.projection_mode == Projection.TOP_DOWN: self.canvas.camera.fov = max(0.5, self.canvas.camera.fov / 1.1) elif evt.action_id == ACT_DECR_SPEED: if self.canvas.camera.projection_mode == Projection.PERSPECTIVE: self.canvas.camera.move_speed /= 1.1 elif self.canvas.camera.projection_mode == Projection.TOP_DOWN: self.canvas.camera.fov = min(1000.0, self.canvas.camera.fov * 1.1) def _on_input_held(self, evt: InputHeldEvent): """Logic to run each time the input held event is run.""" forward = up = right = pitch = yaw = 0 up += (ACT_MOVE_UP in evt.action_ids) - (ACT_MOVE_DOWN in evt.action_ids) forward += (ACT_MOVE_FORWARDS in evt.action_ids) - ( ACT_MOVE_BACKWARDS in evt.action_ids ) right += (ACT_MOVE_RIGHT in evt.action_ids) - (ACT_MOVE_LEFT in evt.action_ids) if self.canvas.camera.projection_mode == Projection.PERSPECTIVE: if self.canvas.camera.rotating: pitch = self.canvas.mouse.delta_y * 0.07 yaw = self.canvas.mouse.delta_x * 0.07 self.canvas.mouse.warp_middle() self.canvas.mouse.reset_delta() self.move_camera_relative(forward, up, right, pitch, yaw) elif self.canvas.camera.projection_mode == Projection.TOP_DOWN: if self.canvas.camera.rotating: width, height = self.canvas.GetSize() width = max(1, width) height = max(1, height) forward += ( 2 * self.canvas.camera.fov * self.canvas.mouse.delta_y / height ) right -= ( 2 * self.canvas.camera.fov * self.canvas.camera.aspect_ratio * self.canvas.mouse.delta_x / width ) self.canvas.mouse.warp_middle() self.canvas.mouse.reset_delta() self.move_camera_relative(forward, up, right, pitch, yaw) else: x, y, z = self.canvas.camera.location x += right * self.canvas.camera.fov / 30 z -= forward * self.canvas.camera.fov / 30 self.canvas.camera.location_rotation = (x, y, z), (180, 90) evt.Skip() def move_camera_relative(self, forward, up, right, pitch, yaw): """Move the camera relative to its current location.""" if not any((forward, up, right, pitch, yaw)): # if not self.canvas.camera.rotating and self._mouse_moved: # self._mouse_moved = False # self._selection_moved = True return x, y, z = self.canvas.camera.location if self.canvas.camera.projection_mode == Projection.PERSPECTIVE: ry, rx = self.canvas.camera.rotation x += self.canvas.camera.move_speed * -( math.cos(math.radians(ry)) * right + math.sin(math.radians(ry)) * forward ) y += self.canvas.camera.move_speed * up z += self.canvas.camera.move_speed * ( math.cos(math.radians(ry)) * forward - math.sin(math.radians(ry)) * right ) rx += self.canvas.camera.rotate_speed * pitch ry += self.canvas.camera.rotate_speed * yaw else: ry, rx = 180, 90 x += right z -= forward self.canvas.camera.location_rotation = (x, y, z), (ry, rx) def _capture_mouse(self): self.canvas.SetCursor(wx.Cursor(wx.CURSOR_BLANK)) self.canvas.mouse.warp_middle() self.canvas.mouse.reset_delta() self.canvas.camera.rotating = True def _release_mouse(self): """Release the mouse""" self.canvas.SetCursor(wx.NullCursor) self.canvas.camera.rotating = False def _on_loss_focus(self, evt): """Event fired when the user tabs out of the window.""" self._escape() evt.Skip() def _escape(self): """Release the mouse and remove all key presses to the camera doesn't fly off into the distance.""" # self._persistent_actions.clear() self.canvas.buttons.unpress_all() self._release_mouse()
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\behaviour\chunk_selection_behaviour.py
from typing import TYPE_CHECKING, Tuple import numpy import time from amulet.api.selection import SelectionGroup, SelectionBox from .pointer_behaviour import PointerBehaviour from amulet_map_editor.api.opengl.mesh.selection import ( RenderSelectionGroup, RenderSelection, ) from ..events import ( InputPressEvent, EVT_INPUT_PRESS, InputReleaseEvent, EVT_INPUT_RELEASE, EVT_SELECTION_CHANGE, ) from amulet_map_editor.api.opengl.camera import Projection from ..key_config import ( ACT_BOX_CLICK, ACT_DESELECT_ALL_BOXES, ACT_DELESECT_BOX, ) if TYPE_CHECKING: from amulet_map_editor.programs.edit.api.canvas import EditCanvas class ChunkSelectionBehaviour(PointerBehaviour): """Adds the behaviour for a chunk based selection.""" def __init__(self, canvas: "EditCanvas"): super().__init__(canvas) self._editing_selection = RenderSelection( self.canvas.context_identifier, self.canvas.renderer.opengl_resource_pack ) self._selection = RenderSelectionGroup( self.canvas.context_identifier, self.canvas.renderer.opengl_resource_pack, ) self._editing = False self._press_time = 0 self._start_box = numpy.zeros((2, 3)) def bind_events(self): super().bind_events() self.canvas.Bind(EVT_INPUT_PRESS, self._on_input_press) self.canvas.Bind(EVT_INPUT_RELEASE, self._on_input_release) self.canvas.Bind(EVT_SELECTION_CHANGE, self._on_selection_change) def _create_undo(self): """Write the current state to the global selection triggering an undo point.""" self.canvas.selection.selection_group = self._selection.selection_group def _chunkify_selection(self): selections = [] for box in self.canvas.selection.selection_group.selection_boxes: min_point = ( numpy.floor(box.min_array / self.canvas.world.sub_chunk_size) * self.canvas.world.sub_chunk_size ) max_point = ( numpy.ceil(box.max_array / self.canvas.world.sub_chunk_size) * self.canvas.world.sub_chunk_size ) bounds = self.canvas.world.bounds(self.canvas.dimension) min_point[1] = bounds.min[1] max_point[1] = bounds.max[1] selections.append(SelectionBox(min_point, max_point)) selection_group = SelectionGroup(selections) if selection_group != self.canvas.selection.selection_group: # if the above code modified the selection self.canvas.selection.selection_group = selection_group # this will indirectly update the renderer by updating the global selection elif selection_group != self._selection.selection_group: # if the above code did not change the selection but it does not match the renderer self._selection.selection_group = selection_group def enable(self): self._chunkify_selection() self._editing = False def _on_selection_change(self, evt): self._chunkify_selection() evt.Skip() def _on_input_press(self, evt: InputPressEvent): if evt.action_id == ACT_BOX_CLICK: if not self._editing: self._press_time = time.time() self._editing = True self._start_box = self._pointer.bounds self._update_pointer() elif evt.action_id == ACT_DESELECT_ALL_BOXES: self._selection.selection_group = SelectionGroup() self._create_undo() elif evt.action_id == ACT_DELESECT_BOX: if ACT_DESELECT_ALL_BOXES not in self.canvas.buttons.pressed_actions: self._selection.selection_group = SelectionGroup() self._create_undo() evt.Skip() def _get_editing_selection(self) -> Tuple[numpy.ndarray, numpy.ndarray]: """Get the minimum and maximum points of the editing selection. This is based on the stored starting pointer and the current pointer.""" points = numpy.concatenate([self._start_box, self._pointer.bounds], 0) return numpy.min(points, 0), numpy.max(points, 0) def _on_input_release(self, evt: InputReleaseEvent): if evt.action_id == ACT_BOX_CLICK: if self._editing and time.time() - self._press_time > 0.1: self._editing = False box = SelectionBox(*self._get_editing_selection()) if SelectionGroup(box).is_subset(self._selection.selection_group): # subtract self._selection.selection_group = ( self._selection.selection_group.subtract(box) ) else: self._selection.selection_group = ( self._selection.selection_group.union(box) ) self._create_undo() evt.Skip() def _update_pointer(self): """Update the pointer and selection location.""" if self.canvas.camera.projection_mode == Projection.TOP_DOWN: x, z = self.get_2d_mouse_location() location = numpy.array([x, 0, z]) else: camera_location = self.canvas.camera.location look_vector = self.look_vector() ( box, max_distance, ) = self._selection.selection_group.closest_vector_intersection( camera_location, look_vector ) location, hit = self.closest_block_3d(min(max_distance, 100)) chunk_size = self.canvas.world.sub_chunk_size location_min: numpy.ndarray = (location // chunk_size) * chunk_size location_max = location_min + chunk_size bounds = self.canvas.world.bounds(self.canvas.dimension) location_min[1] = bounds.min[1] location_max[1] = bounds.max[1] self._pointer.point1, self._pointer.point2 = location_min, location_max if self._editing: ( self._editing_selection.point1, self._editing_selection.point2, ) = self._get_editing_selection() def draw(self): if self.canvas.camera.projection_mode == Projection.TOP_DOWN: camera = None else: camera = self.canvas.camera.location self._selection.draw(self.canvas.camera.transformation_matrix, camera) if self._editing: self._editing_selection.draw( self.canvas.camera.transformation_matrix, camera ) super().draw()
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\behaviour\inspect_block_behaviour.py
from typing import TYPE_CHECKING import logging import wx from wx.adv import RichToolTip from amulet.api.chunk.biomes import BiomesShape from .base_behaviour import BaseBehaviour from .pointer_behaviour import PointerBehaviour from ..events import ( InputPressEvent, EVT_INPUT_PRESS, ) from ..key_config import ( ACT_INSPECT_BLOCK, ) if TYPE_CHECKING: from ..canvas import EditCanvas log = logging.getLogger(__name__) class InspectBlockBehaviour(BaseBehaviour): """Adds a popup with block information.""" def __init__(self, canvas: "EditCanvas", pointer_behaviour: PointerBehaviour): super().__init__(canvas) self._pointer_behaviour = pointer_behaviour def bind_events(self): """Set up all events required to run.""" self.canvas.Bind(EVT_INPUT_PRESS, self._on_input_press) def _on_input_press(self, evt: InputPressEvent): """Logic to run each time the input press event is run.""" if evt.action_id == ACT_INSPECT_BLOCK: self._inspect_block() evt.Skip() def _inspect_block(self): def truncate(s: str, max_line_length: int = None) -> str: if isinstance(max_line_length, int): max_line_length = max(-1, max_line_length) s = "\n".join( [ ( line[: max_line_length - 3] + "..." if len(line) > max_line_length else line ) for line in s.split("\n") ] ) return s full_msg = self._get_block_info_message() msg = truncate(full_msg, 150) tooltip = RichToolTip("Inspect Block", msg) x, y = self.canvas.mouse.xy tooltip.ShowFor(self.canvas, wx.Rect(x, y, 1, 1)) def _get_block_info_message(self) -> str: x, y, z = self._pointer_behaviour.pointer_base try: block = self.canvas.world.get_block(x, y, z, self.canvas.dimension) chunk = self.canvas.world.get_chunk(x >> 4, z >> 4, self.canvas.dimension) block_entity = chunk.block_entities.get((x, y, z), None) platform = self.canvas.world.level_wrapper.platform version = self.canvas.world.level_wrapper.version translator = self.canvas.world.translation_manager.get_version( platform, version, ) ( version_block, version_block_entity, _, ) = translator.block.from_universal( block, block_entity, block_location=(x, y, z) ) if isinstance(version, tuple): version_str = ".".join(str(v) for v in version[:4]) else: version_str = str(version) block_data_text = f"x: {x}, y: {y}, z: {z}\n\n{platform.capitalize()} {version_str}\n{version_block}" if version_block_entity: version_block_entity_str = str(version_block_entity) block_data_text = f"{block_data_text}\n{version_block_entity_str}" block_data_text = f"{block_data_text}\n\nUniversal\n{block}" if block_entity: block_entity_str = str(block_entity) block_data_text = f"{block_data_text}\n{block_entity_str}" if chunk.biomes.dimension == BiomesShape.Shape2D: biome = chunk.biomes[x % 16, z % 16] try: block_data_text = f"{block_data_text}\n\nBiome: {self.canvas.world.biome_palette[biome]}" except Exception as e: log.error(e) elif chunk.biomes.dimension == BiomesShape.Shape3D: biome = chunk.biomes[(x % 16) // 4, y // 4, (z % 16) // 4] try: block_data_text = f"{block_data_text}\n\nBiome: {self.canvas.world.biome_palette[biome]}" except Exception as e: log.error(e) except Exception as e: log.error(e) return str(e) else: return block_data_text
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\behaviour\pointer_behaviour.py
from typing import TYPE_CHECKING import wx from amulet_map_editor.api.opengl.mesh.selection import RenderSelection from amulet_map_editor.api.opengl.camera import Projection from amulet.api.data_types import BlockCoordinatesNDArray, BlockCoordinates from .raycast_behaviour import RaycastBehaviour from ..events import ( EVT_PRE_DRAW, EVT_CAMERA_MOVED, InputPressEvent, EVT_INPUT_PRESS, ) from ..key_config import ( ACT_INCR_SELECT_DISTANCE, ACT_DECR_SELECT_DISTANCE, ) if TYPE_CHECKING: from amulet_map_editor.programs.edit.api.canvas import EditCanvas _PointChangeEventType = wx.NewEventType() EVT_POINT_CHANGE = wx.PyEventBinder(_PointChangeEventType) class PointChangeEvent(wx.PyEvent): """Run when the cursor point changed.""" def __init__(self, point: BlockCoordinates): wx.PyEvent.__init__(self, eventType=_PointChangeEventType) self._point = point @property def point(self) -> BlockCoordinates: return self._point class PointerBehaviour(RaycastBehaviour): """Adds the behaviour of the selection pointer.""" def __init__(self, canvas: "EditCanvas"): super().__init__(canvas) # has the pointer moved self._pointer_moved = True # the distance between the camera and the pointer self._pointer_distance = 10 # the pointer self._pointer = RenderSelection( self.canvas.context_identifier, self.canvas.renderer.opengl_resource_pack, ) @property def pointer_base(self) -> BlockCoordinatesNDArray: return self._pointer.point1 def bind_events(self): super().bind_events() self.canvas.Bind(EVT_PRE_DRAW, self._pre_draw) self.canvas.Bind(EVT_CAMERA_MOVED, self._invalidate_pointer) self.canvas.Bind(wx.EVT_MOTION, self._invalidate_pointer) self.canvas.Bind(EVT_INPUT_PRESS, self._on_input_press) def _on_input_press(self, evt: InputPressEvent): if evt.action_id == ACT_INCR_SELECT_DISTANCE: self._pointer_distance += 1 self._pointer_moved = True elif evt.action_id == ACT_DECR_SELECT_DISTANCE: self._pointer_distance -= 1 self._pointer_moved = True evt.Skip() def _invalidate_pointer(self, evt): self._pointer_moved = True evt.Skip() def _pre_draw(self, evt): if self._pointer_moved: self._update_pointer() self._pointer_moved = False evt.Skip() def _post_change_event(self): wx.PostEvent( self.canvas, PointChangeEvent(tuple(self._pointer.point1.tolist())) ) def _update_pointer(self): """Update the pointer location.""" if self.canvas.camera.projection_mode == Projection.TOP_DOWN: location = self.closest_block_2d()[0] else: if self.canvas.camera.rotating: location = self.distance_block_3d(self._pointer_distance) else: location = self.closest_block_3d()[0] self._pointer.point1, self._pointer.point2 = location, location + 1 self._post_change_event() def draw(self): self._pointer.draw(self.canvas.camera.transformation_matrix)
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\behaviour\raycast_behaviour.py
from typing import TYPE_CHECKING, Optional, Tuple, Generator, List import numpy import math from amulet.api.chunk import Chunk from amulet.api.block import UniversalAirLikeBlocks from amulet.api.errors import ChunkLoadError from amulet_map_editor.api.opengl.matrix import rotation_matrix_xy from amulet.api.data_types import PointCoordinatesNDArray from .base_behaviour import BaseBehaviour if TYPE_CHECKING: from amulet_map_editor.programs.edit.api.canvas import EditCanvas class RaycastBehaviour(BaseBehaviour): """Adds the base behaviour for behaviours that needs to do ray casting.""" def __init__(self, canvas: "EditCanvas"): super().__init__(canvas) def look_vector(self) -> numpy.ndarray: """ The x,y,z vector for the direction the camera is facing :return: (x, y, z) numpy float array ranging from -1 to 1 """ look_vector = numpy.array([0, 0, 1, 0]) if self.canvas.mouse.delta_xy != (0, 0): screen_width, screen_height = numpy.array(self.canvas.GetSize(), int) / 2 screen_width = max(1, screen_width) screen_height = max(1, screen_height) screen_dx = math.atan( self.canvas.mouse.delta_x * self.canvas.camera.aspect_ratio * math.tan(math.radians(self.canvas.camera.fov / 2)) / screen_width ) screen_dy = math.atan( self.canvas.mouse.delta_y * math.cos(screen_dx) * math.tan(math.radians(self.canvas.camera.fov / 2)) / screen_height ) look_vector = numpy.matmul( rotation_matrix_xy(screen_dy, -screen_dx), look_vector, ) ry, rx = self.canvas.camera.rotation look_vector = numpy.matmul( rotation_matrix_xy(*numpy.radians([rx, -ry])), look_vector )[:3] look_vector[abs(look_vector) < 0.000001] = 0.000001 return look_vector def closest_block_3d( self, max_distance: float = 100 ) -> Tuple[PointCoordinatesNDArray, bool]: """Find the location of the closest non-air block. If the end is reached an a non-air block was not found the end location will be returned. :param max_distance: The distance to search up to. :return: Tuple[The block coordinate, was a non-air block found in the range] """ cx: Optional[int] = None cz: Optional[int] = None chunk: Optional[Chunk] = None in_air = False location = numpy.array([0, 0, 0], dtype=numpy.int32) for location in self.collision_locations(max_distance): x, y, z = location cx_ = x >> 4 cz_ = z >> 4 if cx is None or cx != cx_ or cz != cz_: cx = cx_ cz = cz_ try: chunk = self.canvas.world.get_chunk(cx, cz, self.canvas.dimension) except ChunkLoadError: chunk = None if ( chunk is not None and chunk.block_palette[chunk.blocks[x % 16, y, z % 16]] not in UniversalAirLikeBlocks ): # the block is not air if in_air: # if we have previously found an air block return location, True elif not in_air: in_air = True return location, False def get_2d_mouse_location(self) -> Tuple[float, float]: """Get the x and z location of the cursor when in 2D mode.""" x, _, z = self.canvas.camera.location width, height = self.canvas.GetSize() width = max(1, width) height = max(1, height) z += 2 * self.canvas.camera.fov * self.canvas.mouse.delta_y / height x += ( 2 * self.canvas.camera.fov * self.canvas.camera.aspect_ratio * self.canvas.mouse.delta_x / width ) x, z = numpy.floor([x, z]) + 0.5 return x, z def closest_block_2d(self, min_y: int = 0) -> Tuple[PointCoordinatesNDArray, bool]: """Find the first non-air block above a given y axis. Note if there are no non-air blocks above the given axis it will return the min_y value :param min_y: The minimum y coordinate to look to. :return: Tuple[The block coordinate, was a non-air block found in the range] """ x, z = self.get_2d_mouse_location() sub_chunk_size = self.canvas.world.sub_chunk_size y = min_y try: chunk = self.canvas.world.get_chunk( int(x // sub_chunk_size), int(z // sub_chunk_size), self.canvas.dimension, ) except ChunkLoadError: pass else: box_max_chunk = int(min_y // sub_chunk_size) sub_chunks = sorted( [cy for cy in chunk.blocks.sub_chunks if cy >= box_max_chunk], reverse=True, ) if sub_chunks: dx, dz = (numpy.floor([x, z]) % sub_chunk_size).astype(numpy.int64) for sy in sub_chunks: blocks = numpy.invert( numpy.isin( chunk.blocks.get_section(sy)[dx, ::-1, dz], UniversalAirLikeBlocks, ) ) if numpy.any(blocks): y = ( sub_chunk_size - 1 - numpy.argmax(blocks) + sy * sub_chunk_size ) y = max(min_y, y) return numpy.asarray((x, y, z)), True return numpy.asarray((x, y, z)), False def distance_block_3d( self, distance: float, start_location: Optional[numpy.ndarray] = None, look_vector: Optional[numpy.ndarray] = None, ) -> PointCoordinatesNDArray: """The first block location along the camera's look vector that is further away than `distance`. :param distance: The distance between the block and the camera. :param start_location: The start location. Defaults to the camera location. :param look_vector: The unit look vector. Defaults to the camera look vector. :return: (x, y, z) numpy array, selection box index """ if look_vector is None: look_vector = self.look_vector() if start_location is None: start_location = self.canvas.camera.location position = numpy.array(start_location, dtype=int) + numpy.floor( look_vector * distance ).astype(int) return position def collision_locations( self, max_distance: float = 100, start_location: Optional[numpy.ndarray] = None, look_vector: Optional[numpy.ndarray] = None, ) -> Generator[numpy.ndarray, None, None]: """ The block locations that the camera's look vector passes through. :param max_distance: The maximum distance along the look vector to traverse. :param start_location: The start location. Defaults to the camera location. :param look_vector: The unit look vector. Defaults to the camera look vector. :return: A generator of (x, y, z) numpy arrays """ if look_vector is None: look_vector = self.look_vector() if start_location is None: start_location = self.canvas.camera.location dx, dy, dz = look_vector vectors = numpy.array( [look_vector / abs(dx), look_vector / abs(dy), look_vector / abs(dz)] ) locations: List[numpy.ndarray] = [] # the location within the block start: numpy.ndarray = numpy.array(start_location, numpy.float32) % 1 for axis in range(3): vector = vectors[axis] vector_size = numpy.sum(vector**2) ** 0.5 # move the start position to the block edge behind the vector if vector[axis] > 0: initial_offset = -vector * start[axis] else: initial_offset = -vector * (1 - start[axis]) block_count = ( max_distance + numpy.sum(initial_offset**2) ** 0.5 - 0.001 ) // vector_size if block_count: blocks = numpy.arange(block_count + 1).reshape(-1, 1) offsets = blocks * vector + initial_offset locations_ = numpy.floor(offsets + start).astype(int) if vector[axis] < 0: locations_[:, axis] -= 1 locations.append(locations_) if locations: collision_locations = numpy.floor(start_location).astype(int) + numpy.array( sorted( numpy.concatenate(locations), key=lambda loc: sum(abs(loc_) for loc_ in loc), ) ) else: collision_locations = start.astype(int).reshape(1, 3) for location in collision_locations: yield location
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\behaviour\static_selection_behaviour.py
from typing import TYPE_CHECKING from amulet_map_editor.api.opengl.mesh.selection import RenderSelectionGroup from ..events import EVT_SELECTION_CHANGE from .base_behaviour import BaseBehaviour from amulet_map_editor.api.opengl.camera import Projection if TYPE_CHECKING: from amulet_map_editor.programs.edit.api.canvas import EditCanvas class StaticSelectionBehaviour(BaseBehaviour): """Adds the logic for a static selection.""" def __init__(self, canvas: "EditCanvas"): super().__init__(canvas) self._selection = RenderSelectionGroup( self.canvas.context_identifier, self.canvas.renderer.opengl_resource_pack, ) def bind_events(self): self.canvas.Bind(EVT_SELECTION_CHANGE, self._on_selection_change) def _on_selection_change(self, evt): """Update the render selection based on the updated selection.""" self.update_selection() evt.Skip() def update_selection(self): """Pull the latest selection from the canvas.""" self._selection.selection_group = self.canvas.selection.selection_group def draw(self): if self.canvas.camera.projection_mode == Projection.TOP_DOWN: camera = None else: camera = self.canvas.camera.location self._selection.draw(self.canvas.camera.transformation_matrix, camera)
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\behaviour\__init__.py
# API layout from .base_behaviour import BaseBehaviour # camera behaviour from .camera_behaviour import CameraBehaviour # ray casting behaviour from .raycast_behaviour import RaycastBehaviour # pointer box behaviour from .pointer_behaviour import PointerBehaviour # static selection from .static_selection_behaviour import StaticSelectionBehaviour # block selection from .block_selection_behaviour import BlockSelectionBehaviour # chunk selection from .chunk_selection_behaviour import ChunkSelectionBehaviour
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\canvas\base_edit_canvas.py
import logging import wx import traceback from OpenGL.GL import ( glClearColor, glViewport, ) import os from typing import Optional, Generator import weakref import sys import time from minecraft_model_reader.api.resource_pack.java.download_resources import ( get_java_vanilla_latest_iter, get_java_vanilla_fix, ) from minecraft_model_reader.api.resource_pack.java import ( JavaResourcePack, ) from minecraft_model_reader.api.resource_pack.bedrock.download_resources import ( get_bedrock_vanilla_latest_iter, get_bedrock_vanilla_fix, ) from minecraft_model_reader.api.resource_pack.bedrock import BedrockResourcePack from minecraft_model_reader.api.resource_pack import ( load_resource_pack, load_resource_pack_manager, ) from amulet.api.player import LOCAL_PLAYER from amulet.api.data_types import OperationYieldType, Dimension from amulet_map_editor import experimental_bedrock_resources from amulet_map_editor.api.opengl.canvas import EventCanvas from amulet_map_editor.api.opengl.resource_pack.resource_pack import OpenGLResourcePack from amulet_map_editor.programs.edit.api.selection import ( SelectionManager, SelectionHistoryManager, ) from amulet_map_editor import lang import amulet_map_editor.programs.edit as amulet_edit from amulet_map_editor.api.opengl.camera import ControllableCamera from amulet_map_editor.api.wx.util.button_input import ButtonInput from amulet_map_editor.api.wx.util.mouse_movement import MouseMovement from amulet_map_editor.api.wx.ui.traceback_dialog import TracebackDialog from ..renderer import Renderer from amulet.api.level import BaseLevel log = logging.getLogger(__name__) class BaseEditCanvas(EventCanvas): """Adds base logic for drawing everything related to the edit program to the canvas. All the user interaction code is implemented in ControllableEditCanvas to make them easier to read. """ background_colour = (0.61, 0.70, 0.85) def __init__(self, parent: wx.Window, world: BaseLevel): super().__init__(parent) self._world = weakref.ref(world) self._selection: Optional[SelectionHistoryManager] = SelectionHistoryManager( SelectionManager(self) ) self.world.history_manager.register(self._selection, False) self._camera: ControllableCamera = ControllableCamera(self) self._camera.move_speed = 2.0 self._camera.rotate_speed = 2.0 self._buttons: ButtonInput = ButtonInput(self) self._mouse: MouseMovement = MouseMovement(self) self._mouse.set_middle() resource_packs_dir = os.path.join(os.environ["DATA_DIR"], "resource_packs") readme_path = os.path.join(resource_packs_dir, "readme.txt") # create the resource packs location os.makedirs(resource_packs_dir, exist_ok=True) if not os.path.isfile(readme_path): with open(readme_path, "w") as f: f.write("Put the Java resource pack you want loaded in here.") self._renderer: Optional[Renderer] = None self._opengl_resource_pack = None def thread_setup(self) -> Generator[OperationYieldType, None, None]: """ Set up objects that take a while to set up. All code in here must be thread safe and not touch the OpenGL state. """ packs = [] resource_packs_dir = os.path.join(os.environ["DATA_DIR"], "resource_packs") user_packs = [ load_resource_pack(os.path.join(resource_packs_dir, rp)) for rp in os.listdir(resource_packs_dir) if os.path.isdir(os.path.join(resource_packs_dir, rp)) ] if ( self.world.level_wrapper.platform == "bedrock" and experimental_bedrock_resources ): packs.append( load_resource_pack( os.path.join( os.path.dirname(amulet_edit.__file__), "amulet_resource_pack", "bedrock", ) ) ) yield 0.1, lang.get( "program_3d_edit.canvas.downloading_bedrock_vanilla_resource_pack" ) gen = get_bedrock_vanilla_latest_iter() try: while True: yield next(gen) * 0.4 + 0.1 except StopIteration as e: packs.append(e.value) yield 0.5, lang.get("program_3d_edit.canvas.loading_resource_packs") packs += [ pack for pack in user_packs if isinstance(pack, BedrockResourcePack) ] packs.append(get_bedrock_vanilla_fix()) translator = self.world.translation_manager.get_version( "bedrock", (999, 0, 0) ) else: packs.append( load_resource_pack( os.path.join( os.path.dirname(amulet_edit.__file__), "amulet_resource_pack", "java", ) ) ) yield 0.1, lang.get( "program_3d_edit.canvas.downloading_java_vanilla_resource_pack" ) while True: gen = get_java_vanilla_latest_iter() try: while True: yield next(gen) * 0.4 + 0.1 except StopIteration as e: packs.append(e.value) break except Exception as e: if sys.platform == "darwin" and "CERTIFICATE_VERIFY_FAILED" in str( e ): msg = lang.get( "program_3d_edit.canvas.java_rp_failed_mac_certificates" ) else: msg = lang.get("program_3d_edit.canvas.java_rp_failed_default") log.error( msg, exc_info=True, ) wait = True tb = traceback.format_exc() def show_error(): nonlocal wait try: dialog = TracebackDialog( self, lang.get("program_3d_edit.canvas.java_rp_failed"), f"{msg}\n{e}", tb, ) dialog.ShowModal() dialog.Destroy() finally: wait = False wx.CallAfter(show_error) while wait: time.sleep(0.1) msg = wx.MessageDialog( self, lang.get("program_3d_edit.canvas.retry_download"), style=wx.YES_NO, ) if msg.ShowModal() == wx.ID_NO: break yield 0.5, lang.get("program_3d_edit.canvas.loading_resource_packs") packs += [pack for pack in user_packs if isinstance(pack, JavaResourcePack)] packs.append(get_java_vanilla_fix()) translator = self.world.translation_manager.get_version("java", (999, 0, 0)) resource_pack = load_resource_pack_manager(packs, load=False) for i in resource_pack.reload(): yield i / 4 + 0.5 self._opengl_resource_pack = OpenGLResourcePack(resource_pack, translator) yield 0.75, lang.get("program_3d_edit.canvas.creating_texture_atlas") for i in self._opengl_resource_pack.setup(): yield i / 4 + 0.75 def post_thread_setup(self) -> Generator[OperationYieldType, None, None]: """ Any logic that needs to be run after everything has been set up. Code here will be run from the main thread. The canvas has still not been shown here so do not touch the OpenGL state. Do this in _init_opengl. """ yield 1.0, lang.get("program_3d_edit.canvas.setting_up_renderer") self._renderer: Optional[Renderer] = Renderer( self, self.world, self.context_identifier, self._opengl_resource_pack, ) def _init_opengl(self): super()._init_opengl() glClearColor(*self.background_colour, 1.0) try: player = self.world.get_player(LOCAL_PLAYER) location, rotation = player.location, player.rotation self.dimension = player.dimension except: location, rotation = (0.0, 100.0, 0.0), (45.0, 45.0) self._camera.location_rotation = location, rotation self._renderer.move_camera(location, rotation) def bind_events(self): """Set up all events required to run. Note this will also bind subclass events.""" self.Bind(wx.EVT_SIZE, self._on_size) self.selection.bind_events() self.buttons.bind_events() self.mouse.bind_events() self.renderer.bind_events() def enable(self): """Enable the canvas and start it working.""" self.SetCurrent(self._context) self.renderer.enable() self.buttons.enable() def disable(self): """Disable the canvas and unload all geometry.""" self.renderer.disable() self.buttons.disable() def is_closeable(self): """Check that the canvas and contained data is safe to be closed.""" return self.renderer.is_closeable() def close(self): """Destroy all contained data so that the window can be safely destroyed.""" self.renderer.close() @property def world(self) -> BaseLevel: """The amulet-core `BaseLevel` subclass representing the "world" that is open.""" return self._world() @property def renderer(self) -> Renderer: """The `Renderer` class that handles the drawable objects and draws them.""" return self._renderer @property def dimension(self) -> Dimension: """The currently loaded dimension in the renderer.""" return self.renderer.dimension @dimension.setter def dimension(self, dimension: Dimension): """Set the currently loaded dimension in the renderer.""" self.renderer.dimension = dimension @property def camera(self) -> ControllableCamera: """A class holding the state of the camera with methods to access and modify the state.""" return self._camera @property def buttons(self) -> ButtonInput: """A class that manages converting button presses into actions based on set keybinds.""" return self._buttons @property def mouse(self) -> MouseMovement: """A class that manages mouse movement.""" return self._mouse @property def selection(self) -> SelectionManager: """A simple class for storing the selection state.""" return self._selection.value def _on_size(self, evt): wx.CallAfter(self._set_size) evt.Skip() def _set_size(self): size = self.GetClientSize() * self.GetContentScaleFactor() width, height = size self.SetCurrent(self._context) glViewport(0, 0, width, height) if height > 0: self.camera.aspect_ratio = width / height else: self.camera.aspect_ratio = 1
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\canvas\edit_canvas.py
import logging import warnings import wx from typing import Callable, TYPE_CHECKING, Any, Generator, Optional from types import GeneratorType from threading import RLock, Thread from .base_edit_canvas import BaseEditCanvas from ...edit import EDIT_CONFIG_ID from ..key_config import ( DefaultKeys, DefaultKeybindGroupId, PresetKeybinds, KeybindGroup, ) import time import traceback from amulet.api.data_types import OperationReturnType, OperationYieldType, Dimension from amulet.api.structure import structure_cache from amulet.api.level import BaseLevel from amulet_map_editor import CONFIG from amulet_map_editor import close_level from amulet_map_editor.api.wx.ui.traceback_dialog import TracebackDialog from amulet_map_editor.programs.edit.api.ui.goto import show_goto from amulet_map_editor.programs.edit.api.ui.tool_manager import ToolManagerSizer from amulet_map_editor.programs.edit.api.operations.errors import ( OperationError, OperationSilentAbort, BaseLoudException, BaseSilentException, ) from amulet_map_editor.programs.edit.plugins.operations.stock_plugins.internal_operations import ( cut, copy, delete, ) from amulet_map_editor.programs.edit.api.events import ( UndoEvent, RedoEvent, CreateUndoEvent, SaveEvent, ToolChangeEvent, EVT_EDIT_CLOSE, ) from amulet_map_editor.programs.edit.api.ui.file import FilePanel if TYPE_CHECKING: from amulet.api.level import BaseLevel log = logging.getLogger(__name__) OperationType = Callable[[], OperationReturnType] def show_loading_dialog( run: OperationType, title: str, message: str, parent: wx.Window ) -> Any: warnings.warn("show_loading_dialog is depreciated.", DeprecationWarning) dialog = wx.ProgressDialog( title, message, maximum=10_000, parent=parent, style=wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME | wx.PD_AUTO_HIDE, ) dialog.Fit() t = time.time() try: obj = run() if isinstance(obj, GeneratorType): try: while True: progress = next(obj) if isinstance(progress, (list, tuple)): if len(progress) >= 2: message = progress[1] if len(progress) >= 1: progress = progress[0] if isinstance(progress, (int, float)) and isinstance(message, str): dialog.Update( min(9999, max(0, int(progress * 10_000))), message ) wx.Yield() except StopIteration as e: obj = e.value except Exception as e: dialog.Update(10_000) raise e time.sleep(max(0.2 - time.time() + t, 0)) dialog.Update(10_000) return obj class OperationThread(Thread): # The operation to run _operation: OperationType # Should the operation be stopped. Set externally stop: bool # The starting message for the progress dialog message: str # The operation progress (from 0-1) progress: float # The return value from the operation out: Any # The error raised if any error: Optional[BaseException] def __init__(self, operation: OperationType, message: str): super().__init__() self._operation = operation self.stop = False self.message = message self.progress = 0.0 self.out = None self.error = None def run(self) -> None: t = time.time() try: obj = self._operation() if isinstance(obj, GeneratorType): try: while True: if self.stop: raise OperationSilentAbort progress = next(obj) if isinstance(progress, (list, tuple)): if len(progress) >= 2: self.message = progress[1] if len(progress) >= 1: self.progress = progress[0] elif isinstance(progress, (int, float)): self.progress = progress except StopIteration as e: self.out = e.value except BaseException as e: self.error = e time.sleep(max(0.2 - time.time() + t, 0)) class EditCanvas(BaseEditCanvas): def __init__(self, parent: wx.Window, world: "BaseLevel"): super().__init__(parent, world) self._file_panel: Optional[FilePanel] = None self._tool_sizer: Optional[ToolManagerSizer] = None self.buttons.register_actions(self.key_binds) self._canvas_sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self._canvas_sizer) # Tracks if an operation has been started and not finished. self._operation_running = False # This lock stops two threads from editing the world simultaneously # call run_operation to acquire it. self._edit_lock = RLock() def _init_opengl(self): super()._init_opengl() self._file_panel = FilePanel(self) self._canvas_sizer.Add(self._file_panel, 0, wx.EXPAND, 0) self._tool_sizer = ToolManagerSizer(self) self._canvas_sizer.Add(self._tool_sizer, 1, wx.EXPAND, 0) def bind_events(self): """Set up all events required to run. Note this will also bind subclass events.""" self._tool_sizer.bind_events() # binding the tool events first will run them last so they can't accidentally block UI events. super().bind_events() self._file_panel.bind_events() self.Bind(EVT_EDIT_CLOSE, self._on_close) def enable(self): super().enable() self._tool_sizer.enable() def disable(self): super().disable() self._tool_sizer.disable() def _on_close(self, _): close_level(self.world.level_path) @property def tools(self): return self._tool_sizer.tools @property def key_binds(self) -> KeybindGroup: config_ = CONFIG.get(EDIT_CONFIG_ID, {}) user_keybinds = config_.get("user_keybinds", {}) group = config_.get("keybind_group", DefaultKeybindGroupId) if group in user_keybinds: return user_keybinds[group] elif group in PresetKeybinds: return PresetKeybinds[group] else: return DefaultKeys def _deselect(self): # TODO: Re-implement this self._tool_sizer.enable_default_tool() def run_operation( self, operation: OperationType, title="Amulet", msg="Running Operation", throw_exceptions=False, ) -> Any: try: out = self._run_operation(operation, title, msg, True) except BaseException as e: if throw_exceptions: raise e else: # If there were no errors create an undo point def create_undo(): yield 0, "Creating Undo Point" yield from self.create_undo_point_iter() self._run_operation(create_undo, title, msg, False) return out def _run_operation( self, operation: OperationType, title: str, msg: str, cancelable: bool, ) -> Any: with self._edit_lock: if self._operation_running: raise Exception( "run_operation cannot be called from within itself. " "This function has already been called by parent code so you cannot run it again" ) self._operation_running = True self.renderer.disable_threads() style = ( wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME | wx.PD_AUTO_HIDE | (wx.PD_CAN_ABORT * cancelable) ) dialog = wx.ProgressDialog( title, msg, maximum=10_000, parent=self, style=style, ) dialog.Fit() # Set up a thread to run the actual operation op = OperationThread(operation, msg) # run the operation op.start() while op.is_alive(): op.join(0.1) dialog.Update(max(0, min(int(op.progress * 10_000), 9999)), op.message) wx.Yield() if dialog.WasCancelled(): op.stop = True dialog.Destroy() wx.Yield() if op.error is not None: # If there is any kind of error restore the last undo point self.world.restore_last_undo_point() if isinstance(op.error, BaseLoudException): msg = str(op.error) if isinstance(op.error, OperationError): msg = f"Error running operation: {msg}" log.info(msg) wx.MessageDialog(self, msg, style=wx.OK).ShowModal() elif isinstance(op.error, BaseSilentException): pass elif isinstance(op.error, BaseException): tb = "".join( traceback.format_exception( type(op.error), op.error, op.error.__traceback__ ) ) log.error(tb) dialog = TracebackDialog( self, "Exception while running operation", str(op.error), tb, ) dialog.ShowModal() dialog.Destroy() self.world.restore_last_undo_point() self.renderer.enable_threads() self.renderer.render_world.rebuild_changed() self._operation_running = False if op.error is not None: raise op.error return op.out def create_undo_point(self, world=True, non_world=True): self.world.create_undo_point(world, non_world) wx.PostEvent(self, CreateUndoEvent()) def create_undo_point_iter( self, world=True, non_world=True ) -> Generator[float, None, bool]: result = yield from self.world.create_undo_point_iter(world, non_world) wx.PostEvent(self, CreateUndoEvent()) return result def undo(self): self.world.undo() self.renderer.render_world.rebuild_changed() wx.PostEvent(self, UndoEvent()) def redo(self): self.world.redo() self.renderer.render_world.rebuild_changed() wx.PostEvent(self, RedoEvent()) def cut(self): self.run_operation( lambda: cut(self.world, self.dimension, self.selection.selection_group) ) def copy(self): self.run_operation( lambda: copy(self.world, self.dimension, self.selection.selection_group) ) def paste(self, structure: BaseLevel, dimension: Dimension): assert isinstance( structure, BaseLevel ), "Structure given is not a subclass of BaseLevel." assert ( dimension in structure.dimensions ), "The requested dimension does not exist for this object." wx.PostEvent( self, ToolChangeEvent( tool="Paste", state={"structure": structure, "dimension": dimension} ), ) def paste_from_cache(self): if structure_cache: self.paste(*structure_cache.get_structure()) else: wx.MessageBox("A structure needs to be copied before one can be pasted.") def delete(self): self.run_operation( lambda: delete(self.world, self.dimension, self.selection.selection_group) ) def goto(self): location = show_goto(self, *self.camera.location) if location: self.camera.location = location def select_all(self): all_chunk_coords = tuple(self.world.all_chunk_coords(self.dimension)) if all_chunk_coords: min_x, min_z = max_x, max_z = all_chunk_coords[0] for x, z in all_chunk_coords: if x < min_x: min_x = x elif x > max_x: max_x = x if z < min_z: min_z = z elif z > max_z: max_z = z self.selection.selection_corners = [ ( ( min_x * self.world.sub_chunk_size, self.world.bounds(self.dimension).min[1], min_z * self.world.sub_chunk_size, ), ( (max_x + 1) * self.world.sub_chunk_size, self.world.bounds(self.dimension).max[1], (max_z + 1) * self.world.sub_chunk_size, ), ) ] else: self.selection.selection_corners = [] def save(self): def save(): yield 0, "Running Pre-Save Operations." pre_save_op = self.world.pre_save_operation() try: while True: yield next(pre_save_op) except StopIteration as e: if e.value: yield from self.create_undo_point_iter() else: self.world.restore_last_undo_point() yield 0, "Saving Chunks." for chunk_index, chunk_count in self.world.save_iter(): yield chunk_index / chunk_count self._run_operation(save, "Saving world.", "Please wait.", False) wx.PostEvent(self, SaveEvent())
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\canvas\__init__.py
from .edit_canvas import EditCanvas
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\operations\errors.py
class BaseOperationException(Exception): pass class BaseLoudException(BaseOperationException): pass class BaseSilentException(BaseOperationException): pass class OperationError(BaseLoudException): """Error to raise if something went wrong when running the operation. Will notify the user with a dialog box with the message f"Error running operation {msg}" Changes will be rolled back to the last backup. Eg. if the operation requires something it is not given""" pass class OperationSuccessful(BaseLoudException): """raise this if you want to exit the operation without creating an undo point. Will notify the user with a dialog box containing the message. Changes will be rolled back to the last backup.""" pass class OperationSilentAbort(BaseSilentException): """Error to raise if something went wrong when running the operation but you do not want the user to see. This error will be handled silently. Changes will be rolled back to the last backup.""" pass
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\operations\__init__.py
from .base import OperationUI, OperationUIType, DefaultOperationUI from .ui.fixed_pipeline import FixedFunctionUI from .errors import OperationError, OperationSuccessful, OperationSilentAbort from .ui.simple_operation_panel import SimpleOperationPanel
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\ui\canvas_toggle_element.py
class CanvasToggleElement: """This is a base class for any UI element that is dropped into the canvas and can be enabled and disabled.""" def enable(self): """Set the state of the UI for being enabled. Do not bind events to the canvas here because they will get removed. Do this in bind_events. """ raise NotImplementedError def bind_events(self): """Bind all required events to the canvas. All events on the canvas will be automatically removed after the UI is disabled. """ raise NotImplementedError def disable(self): """Stop the UI. Unload any excessive data. May get resumed again with a call to enable. All events bound to the canvas will be automatically removed after this is run. """ raise NotImplementedError
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\ui\file.py
from typing import TYPE_CHECKING, Optional from math import floor, log10 import wx from amulet_map_editor.programs.edit.api.edit_canvas_container import ( EditCanvasContainer, ) from amulet_map_editor.api.wx.ui.simple import SimpleChoiceAny from amulet_map_editor.programs.edit.api.events import ( EVT_CAMERA_MOVED, EVT_SPEED_CHANGED, EVT_UNDO, EVT_REDO, EVT_CREATE_UNDO, EVT_SAVE, EVT_PROJECTION_CHANGED, EVT_DIMENSION_CHANGE, DimensionChangeEvent, EditCloseEvent, ) from amulet_map_editor.api import image, lang from amulet_map_editor.api.opengl.camera import Projection if TYPE_CHECKING: from amulet_map_editor.programs.edit.api.canvas import EditCanvas def _format_float(num: float) -> str: if num < 100: return f"{num:.0{max(0, 2 - floor(log10(num)))}f}".rstrip("0").rstrip(".") else: return f"{num:.0f}" class FilePanel(wx.BoxSizer, EditCanvasContainer): def __init__(self, canvas: "EditCanvas"): wx.BoxSizer.__init__(self, wx.HORIZONTAL) EditCanvasContainer.__init__(self, canvas) level = self.canvas.world self._version_text = wx.StaticText( canvas, label=f"{level.level_wrapper.platform}, {level.level_wrapper.version}", ) self._version_text.SetToolTip( lang.get("program_3d_edit.file_ui.version_tooltip") ) self.Add(self._version_text, 0) self.AddStretchSpacer(1) self._projection_button = wx.Button(canvas, label="3D") self._projection_button.SetToolTip( lang.get("program_3d_edit.file_ui.projection_tooltip") ) self._projection_button.Bind(wx.EVT_BUTTON, self._on_projection_button) self.Add( self._projection_button, 0, wx.TOP | wx.BOTTOM | wx.RIGHT | wx.CENTER, 5 ) self._location_button = wx.Button( canvas, label=", ".join([f"{s:.2f}" for s in self.canvas.camera.location]) ) self._location_button.SetToolTip( lang.get("program_3d_edit.file_ui.location_tooltip") ) self._location_button.Bind(wx.EVT_BUTTON, lambda evt: self.canvas.goto()) self.Add(self._location_button, 0, wx.TOP | wx.BOTTOM | wx.RIGHT | wx.CENTER, 5) def set_speed(evt): dialog = SpeedSelectDialog( canvas, self.canvas.camera.move_speed * 1000 / 33 ) if dialog.ShowModal() == wx.ID_OK: self.canvas.camera.move_speed = dialog.speed * 33 / 1000 self._speed_button = wx.Button( canvas, label=f"{_format_float(self.canvas.camera.move_speed * 1000 / 33)} {lang.get('program_3d_edit.file_ui.speed_blocks_per_second')}", ) self._speed_button.SetToolTip(lang.get("program_3d_edit.file_ui.speed_tooltip")) self._speed_button.Bind(wx.EVT_BUTTON, set_speed) self.Add(self._speed_button, 0, wx.TOP | wx.BOTTOM | wx.RIGHT | wx.CENTER, 5) self._dim_options = SimpleChoiceAny(canvas) self._dim_options.SetToolTip(lang.get("program_3d_edit.file_ui.dim_tooltip")) self._dim_options.SetItems(level.level_wrapper.dimensions) self._set_dimension(canvas.dimension) self._dim_options.Bind(wx.EVT_CHOICE, self._on_dimension_change) self.Add(self._dim_options, 0, wx.TOP | wx.BOTTOM | wx.RIGHT | wx.CENTER, 5) def create_button(text, operation): button = wx.Button(canvas, label=text) button.Bind(wx.EVT_BUTTON, operation) self.Add(button, 0, wx.TOP | wx.BOTTOM | wx.RIGHT, 5) return button self._undo_button: Optional[wx.Button] = create_button( "0", lambda evt: self.canvas.undo() ) self._undo_button.SetBitmap(image.icon.tablericons.arrow_back_up.bitmap(20, 20)) self._undo_button.SetToolTip(lang.get("program_3d_edit.file_ui.undo_tooltip")) self._redo_button: Optional[wx.Button] = create_button( "0", lambda evt: self.canvas.redo() ) self._redo_button.SetBitmap( image.icon.tablericons.arrow_forward_up.bitmap(20, 20) ) self._redo_button.SetToolTip(lang.get("program_3d_edit.file_ui.redo_tooltip")) self._save_button: Optional[wx.Button] = create_button( "0", lambda evt: self.canvas.save() ) self._save_button.SetBitmap(image.icon.tablericons.device_floppy.bitmap(20, 20)) self._save_button.SetToolTip(lang.get("program_3d_edit.file_ui.save_tooltip")) close_button = wx.BitmapButton( canvas, bitmap=image.icon.tablericons.square_x.bitmap(20, 20) ) close_button.SetToolTip(lang.get("program_3d_edit.file_ui.close_tooltip")) close_button.Bind( wx.EVT_BUTTON, lambda evt: wx.PostEvent(self.canvas, EditCloseEvent()) ) self.Add(close_button, 0, wx.TOP | wx.BOTTOM | wx.RIGHT, 5) self._update_buttons() self.Layout() def bind_events(self): self.canvas.Bind(EVT_CAMERA_MOVED, self._on_camera_move) self.canvas.Bind(EVT_SPEED_CHANGED, self._on_speed_change) self.canvas.Bind(EVT_UNDO, self._on_update_buttons) self.canvas.Bind(EVT_REDO, self._on_update_buttons) self.canvas.Bind(EVT_SAVE, self._on_update_buttons) self.canvas.Bind(EVT_CREATE_UNDO, self._on_update_buttons) self.canvas.Bind(EVT_PROJECTION_CHANGED, self._on_projection_change) self.canvas.Bind(EVT_DIMENSION_CHANGE, self._change_dimension) def _on_update_buttons(self, evt): self._update_buttons() evt.Skip() def _update_buttons(self): self._undo_button.SetLabel(f"{self.canvas.world.history_manager.undo_count}") self._redo_button.SetLabel(f"{self.canvas.world.history_manager.redo_count}") self._save_button.SetLabel( f"{self.canvas.world.history_manager.unsaved_changes}" ) def _on_dimension_change(self, evt): """Run when the dimension selection is changed by the user.""" dimension = self._dim_options.GetCurrentObject() if dimension is not None: self.canvas.dimension = dimension evt.Skip() def _on_projection_change(self, evt): if self.canvas.camera.projection_mode == Projection.PERSPECTIVE: self._projection_button.SetLabel("3D") elif self.canvas.camera.projection_mode == Projection.TOP_DOWN: self._projection_button.SetLabel("2D") evt.Skip() def _on_projection_button(self, evt): if self.canvas.camera.projection_mode == Projection.PERSPECTIVE: self.canvas.camera.projection_mode = Projection.TOP_DOWN else: self.canvas.camera.projection_mode = Projection.PERSPECTIVE evt.Skip() def _change_dimension(self, evt: DimensionChangeEvent): """Run when the dimension attribute in the canvas is changed. This is run when the user changes the attribute and when it is changed manually in code. """ self._set_dimension(evt.dimension) def _set_dimension(self, dimension: str) -> None: index = self._dim_options.FindString(dimension) if not (index == wx.NOT_FOUND or index == self._dim_options.GetSelection()): self._dim_options.SetSelection(index) def _on_camera_move(self, evt): x, y, z = evt.camera_location label = f"{x:.2f}, {y:.2f}, {z:.2f}" old_label = self._location_button.GetLabel() self._location_button.SetLabel(label) if len(label) != len(old_label): self.canvas.Layout() evt.Skip() def _on_speed_change(self, evt): label = f"{_format_float(self.canvas.camera.move_speed * 1000 / 33)} {lang.get('program_3d_edit.file_ui.speed_blocks_per_second')}" old_label = self._speed_button.GetLabel() self._speed_button.SetLabel(label) if len(label) != len(old_label): self.canvas.Layout() evt.Skip() class SpeedSelectDialog(wx.Dialog): def __init__(self, parent: wx.Window, speed: float): wx.Dialog.__init__(self, parent) self.SetTitle(lang.get("program_3d_edit.file_ui.speed_dialog_name")) sizer = wx.BoxSizer(wx.VERTICAL) self._speed_spin_ctrl_double = wx.SpinCtrlDouble( self, wx.ID_ANY, initial=speed, min=0.0, max=1_000_000_000.0 ) self._speed_spin_ctrl_double.SetToolTip( lang.get("program_3d_edit.file_ui.speed_tooltip") ) def on_mouse_wheel(evt: wx.MouseEvent): if evt.GetWheelRotation() > 0: self._speed_spin_ctrl_double.SetValue( self._speed_spin_ctrl_double.GetValue() + self._speed_spin_ctrl_double.GetIncrement() ) else: self._speed_spin_ctrl_double.SetValue( self._speed_spin_ctrl_double.GetValue() - self._speed_spin_ctrl_double.GetIncrement() ) self._speed_spin_ctrl_double.Bind(wx.EVT_MOUSEWHEEL, on_mouse_wheel) self._speed_spin_ctrl_double.SetIncrement(1.0) self._speed_spin_ctrl_double.SetDigits(4) sizer.Add( self._speed_spin_ctrl_double, 0, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 5 ) button_sizer = wx.StdDialogButtonSizer() sizer.Add(button_sizer, 0, wx.ALIGN_RIGHT | wx.ALL, 4) self._button_ok = wx.Button(self, wx.ID_OK, "") self._button_ok.SetDefault() button_sizer.AddButton(self._button_ok) self._button_cancel = wx.Button(self, wx.ID_CANCEL, "") button_sizer.AddButton(self._button_cancel) button_sizer.Realize() self.SetSizer(sizer) sizer.Fit(self) self.SetAffirmativeId(self._button_ok.GetId()) self.SetEscapeId(self._button_cancel.GetId()) self.Layout() @property def speed(self) -> float: return self._speed_spin_ctrl_double.GetValue()
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\ui\goto.py
from typing import Optional, Tuple import wx import re from amulet.api.data_types import PointCoordinates from amulet_map_editor import lang from amulet_map_editor.api.wx.ui.simple import SimpleDialog from amulet_map_editor.api import image CoordRegex = re.compile( r"^" # match the start r"\s*" # leading whitespace r"(?P<x>-?[0-9]+\.?[0-9]*)" # the x coordinate r"((?:,\s*)|(?:\s+))" # separator 1 r"(?P<y>-?[0-9]+\.?[0-9]*)" # the y coordinate r"((?:,\s*)|(?:\s+))" # separator 2 r"(?P<z>-?[0-9]+\.?[0-9]*)" # the z coordinate r",?\s*" # trailing comma and whitespace r"$" # matches the end ) def show_goto( parent: wx.Window, x: float, y: float, z: float ) -> Optional[Tuple[float, float, float]]: dialog = GoTo(parent, lang.get("program_3d_edit.goto_ui.title"), (x, y, z)) if dialog.ShowModal() == wx.ID_OK: return dialog.location class GoTo(SimpleDialog): def __init__(self, parent: wx.Window, title: str, start: PointCoordinates): super().__init__(parent, title, wx.HORIZONTAL) x, y, z = start x_text = wx.StaticText(self, label=lang.get("program_3d_edit.goto_ui.x_label")) self.x = wx.SpinCtrlDouble(self, min=-30000000, max=30000000, initial=x) self.x.SetToolTip(lang.get("program_3d_edit.goto_ui.x_label_tooltip")) self.x.SetDigits(2) y_text = wx.StaticText(self, label=lang.get("program_3d_edit.goto_ui.y_label")) self.y = wx.SpinCtrlDouble(self, min=-30000000, max=30000000, initial=y) self.y.SetToolTip(lang.get("program_3d_edit.goto_ui.y_label_tooltip")) self.y.SetDigits(2) z_text = wx.StaticText(self, label=lang.get("program_3d_edit.goto_ui.z_label")) self.z = wx.SpinCtrlDouble(self, min=-30000000, max=30000000, initial=z) self.z.SetToolTip(lang.get("program_3d_edit.goto_ui.z_label_tooltip")) self.z.SetDigits(2) self.sizer.Add(x_text, 0, wx.CENTER | wx.ALL, 5) self.sizer.Add(self.x, 1, wx.CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT, 5) self.sizer.Add(y_text, 0, wx.CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT, 5) self.sizer.Add(self.y, 1, wx.CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT, 5) self.sizer.Add(z_text, 0, wx.CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT, 5) self.sizer.Add(self.z, 1, wx.CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT, 5) self.x.Bind(wx.EVT_CHAR, self._on_text) self.y.Bind(wx.EVT_CHAR, self._on_text) self.z.Bind(wx.EVT_CHAR, self._on_text) copy_button = wx.BitmapButton( self, bitmap=image.icon.tablericons.copy.bitmap(20, 20) ) copy_button.Bind(wx.EVT_BUTTON, lambda evt: self._copy()) copy_button.SetToolTip(lang.get("program_3d_edit.goto_ui.copy_button_tooltip")) self.bottom_sizer.Insert(0, copy_button, 0, wx.ALL, 5) paste_button = wx.BitmapButton( self, bitmap=image.icon.tablericons.clipboard.bitmap(20, 20) ) paste_button.Bind(wx.EVT_BUTTON, lambda evt: self._paste()) paste_button.SetToolTip( lang.get("program_3d_edit.goto_ui.paste_button_tooltip") ) self.bottom_sizer.Insert(1, paste_button, 0, wx.TOP | wx.BOTTOM | wx.RIGHT, 5) self.Fit() @property def location(self) -> PointCoordinates: return self.x.GetValue(), self.y.GetValue(), self.z.GetValue() def _on_text(self, evt): if evt.ControlDown() and evt.GetKeyCode() == 3: # Ctrl+C self._copy() elif evt.ControlDown() and evt.GetKeyCode() == 22: # Ctrl+V if not self._paste(): evt.Skip() else: evt.Skip() def _copy(self): if wx.TheClipboard.Open(): wx.TheClipboard.SetData( wx.TextDataObject( "{} {} {}".format( round(self.x.GetValue(), 5), round(self.y.GetValue(), 5), round(self.z.GetValue(), 5), ) ) ) wx.TheClipboard.Close() def _paste(self) -> bool: text = "" text_data = wx.TextDataObject() if wx.TheClipboard.Open(): success = wx.TheClipboard.GetData(text_data) wx.TheClipboard.Close() if success: text = text_data.GetText() match = CoordRegex.fullmatch(text) if match: self.x.SetValue(float(match.group("x"))) self.y.SetValue(float(match.group("y"))) self.z.SetValue(float(match.group("z"))) return True return False
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\ui\nudge_button.py
from typing import Tuple import wx import weakref import numpy import math from amulet_map_editor.api.opengl.camera import Camera from amulet_map_editor.api.opengl.matrix import rotation_matrix_xy from amulet_map_editor.programs.edit.api.key_config import ( KeybindGroup, ACT_MOVE_UP, ACT_MOVE_DOWN, ACT_MOVE_FORWARDS, ACT_MOVE_BACKWARDS, ACT_MOVE_LEFT, ACT_MOVE_RIGHT, ACT_BOX_CLICK, ) from amulet_map_editor.api.wx.util.button_input import ( ButtonInput, InputPressEvent, EVT_INPUT_PRESS, InputReleaseEvent, EVT_INPUT_RELEASE, InputHeldEvent, EVT_INPUT_HELD, ) _MoveActions = { ACT_MOVE_UP, ACT_MOVE_DOWN, ACT_MOVE_FORWARDS, ACT_MOVE_BACKWARDS, ACT_MOVE_LEFT, ACT_MOVE_RIGHT, } class NudgeButton(wx.Button): """A button that catches actions when pressed.""" def __init__( self, parent: wx.Window, camera: Camera, keybinds: KeybindGroup, label: str, tooltip: str, ): super().__init__(parent, label=label, style=wx.WANTS_CHARS) self.SetToolTip(tooltip) self._camera = weakref.ref(camera) self._buttons = ButtonInput(self) self._buttons.register_actions(keybinds) self._buttons.bind_events() # this is fine here because we are binding to a custom button not the canvas. self.Bind(EVT_INPUT_PRESS, self._on_down) self.Bind(EVT_INPUT_RELEASE, self._on_up) self.Bind(EVT_INPUT_HELD, self._on_held) self._listen = False self._timeout = 10 @property def camera(self) -> Camera: return self._camera() def enable(self): self._buttons.enable() def disable(self): self._buttons.disable() def _on_down(self, evt: InputPressEvent): if evt.action_id == ACT_BOX_CLICK: self._listen = True elif evt.action_id in _MoveActions: self._timeout = 10 def _on_up(self, evt: InputReleaseEvent): if evt.action_id == ACT_BOX_CLICK: self._listen = False def _on_held(self, evt: InputHeldEvent): if self._listen: if self._timeout == 0 or self._timeout == 10: x = y = z = 0 if ACT_MOVE_LEFT in evt.action_ids: x += 1 if ACT_MOVE_RIGHT in evt.action_ids: x -= 1 if ACT_MOVE_UP in evt.action_ids: y += 1 if ACT_MOVE_DOWN in evt.action_ids: y -= 1 if ACT_MOVE_FORWARDS in evt.action_ids: z += 1 if ACT_MOVE_BACKWARDS in evt.action_ids: z -= 1 if any((x, y, z)): self._move(self._rotate((x, y, z))) if self._timeout: self._timeout -= 1 def _rotate(self, offset: Tuple[int, int, int]) -> Tuple[int, int, int]: x, y, z = offset ry = self.camera.rotation[0] x, y, z, _ = ( numpy.round( numpy.matmul( rotation_matrix_xy(0, -math.radians(round(ry / 90) * 90)), (x, y, z, 0), ) ) .astype(int) .tolist() ) return x, y, z def _move(self, offset: Tuple[int, int, int]): pass
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\ui\tool_manager.py
import wx from typing import TYPE_CHECKING, Type, Dict, Optional from amulet_map_editor.programs.edit.api import EditCanvasContainer from amulet_map_editor.programs.edit.api.ui.tool.base_tool_ui import ( BaseToolUI, BaseToolUIType, ) from amulet_map_editor.programs.edit.api.events import ( ToolChangeEvent, EVT_TOOL_CHANGE, ) from amulet_map_editor.programs.edit.plugins.tools import ( ImportTool, ExportTool, OperationTool, SelectTool, ChunkTool, PasteTool, ) if TYPE_CHECKING: from amulet_map_editor.programs.edit.api.canvas import EditCanvas class ToolManagerSizer(wx.BoxSizer, EditCanvasContainer): def __init__(self, canvas: "EditCanvas"): wx.BoxSizer.__init__(self, wx.VERTICAL) EditCanvasContainer.__init__(self, canvas) self._tools: Dict[str, BaseToolUIType] = {} self._active_tool: Optional[BaseToolUIType] = None self._tool_option_sizer = wx.BoxSizer(wx.VERTICAL) self.Add( self._tool_option_sizer, 1, wx.EXPAND | wx.RESERVE_SPACE_EVEN_IF_HIDDEN, 0 ) tool_select_sizer = wx.BoxSizer(wx.HORIZONTAL) tool_select_sizer.AddStretchSpacer(1) self._tool_select = ToolSelect(canvas) tool_select_sizer.Add(self._tool_select, 0, wx.EXPAND, 0) tool_select_sizer.AddStretchSpacer(1) self.Add(tool_select_sizer, 0, wx.EXPAND, 0) self.register_tool(SelectTool) self.register_tool(PasteTool) self.register_tool(OperationTool) self.register_tool(ImportTool) self.register_tool(ExportTool) self.register_tool(ChunkTool) @property def tools(self): return self._tools.copy() def bind_events(self): if self._active_tool is not None: self._active_tool.bind_events() self.canvas.Bind(EVT_TOOL_CHANGE, self._enable_tool_event) def register_tool(self, tool_cls: Type[BaseToolUIType]): assert issubclass(tool_cls, (wx.Window, wx.Sizer)) and issubclass( tool_cls, BaseToolUI ) tool = tool_cls(self.canvas) self._tool_select.register_tool(tool.name) if isinstance(tool, wx.Window): tool.Hide() elif isinstance(tool, wx.Sizer): tool.ShowItems(show=False) self._tools[tool.name] = tool self._tool_option_sizer.Add(tool, 1, wx.EXPAND, 0) def _enable_tool_event(self, evt: ToolChangeEvent): self._enable_tool(evt.tool, evt.state) def enable(self): if isinstance(self._active_tool, SelectTool): self._active_tool.enable() self.canvas.reset_bound_events() self.canvas.Layout() else: self._enable_tool("Select") def disable(self): """Disable the active tool.""" if self._active_tool is not None: self._active_tool.disable() def enable_default_tool(self): """ Enables the default tool (the select tool) """ if not isinstance(self._active_tool, SelectTool): self._enable_tool("Select") def _enable_tool(self, tool: str, state=None): if tool in self._tools: if self._active_tool is not None: self._active_tool.disable() if isinstance(self._active_tool, wx.Window): self._active_tool.Hide() elif isinstance(self._active_tool, wx.Sizer): self._active_tool.ShowItems(show=False) self._active_tool = self._tools[tool] if isinstance(self._active_tool, wx.Window): self._active_tool.Show() elif isinstance(self._active_tool, wx.Sizer): self._active_tool.ShowItems(show=True) self._active_tool.enable() self._active_tool.set_state(state) self.canvas.reset_bound_events() self.canvas.Layout() class ToolSelect(wx.Panel, EditCanvasContainer): def __init__(self, canvas: "EditCanvas"): wx.Panel.__init__(self, canvas) EditCanvasContainer.__init__(self, canvas) self._sizer = wx.BoxSizer(wx.HORIZONTAL) self.SetSizer(self._sizer) def register_tool(self, name: str): button = wx.Button(self, label=name) self._sizer.Add(button) self._sizer.Fit(self) self.Layout() button.Bind( wx.EVT_BUTTON, lambda evt: wx.PostEvent(self.canvas, ToolChangeEvent(tool=name)), )
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\ui\__init__.py
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\operations\base\default_operation_ui.py
from typing import TYPE_CHECKING import wx from OpenGL.GL import ( glClear, GL_DEPTH_BUFFER_BIT, ) from .operation_ui import OperationUI from amulet_map_editor.programs.edit.api.behaviour import StaticSelectionBehaviour from amulet_map_editor.api.opengl.camera import Projection from amulet_map_editor.programs.edit.api.events import EVT_DRAW from amulet_map_editor.programs.edit.api.behaviour import ( CameraBehaviour, PointerBehaviour, ) from amulet_map_editor.programs.edit.api.events import ( InputPressEvent, EVT_INPUT_PRESS, ) from amulet_map_editor.programs.edit.api.key_config import ( ACT_BOX_CLICK, ) if TYPE_CHECKING: from amulet_map_editor.programs.edit.api.canvas import EditCanvas from amulet.api.level import BaseLevel class DefaultOperationUI(OperationUI): """An extension of the base OperationUI that adds camera, static selection and some other controls.""" def __init__( self, parent: wx.Window, canvas: "EditCanvas", world: "BaseLevel", options_path: str, ): super().__init__(parent, canvas, world, options_path) self._selection = StaticSelectionBehaviour(self.canvas) self._camera_behaviour = CameraBehaviour(self.canvas) self._pointer = PointerBehaviour(self.canvas) self._show_pointer = False def enable(self): self._selection.update_selection() self.canvas.camera.projection_mode = Projection.PERSPECTIVE def bind_events(self): self._selection.bind_events() self.canvas.Bind(EVT_DRAW, self._on_draw) self._camera_behaviour.bind_events() self._pointer.bind_events() self.canvas.Bind(EVT_INPUT_PRESS, self._on_input_press) def _on_draw(self, evt): self.canvas.renderer.start_draw() if self.canvas.camera.projection_mode == Projection.PERSPECTIVE: self.canvas.renderer.draw_sky_box() glClear(GL_DEPTH_BUFFER_BIT) self.canvas.renderer.draw_level() self._selection.draw() if self._show_pointer: self._pointer.draw() self.canvas.renderer.end_draw() def _on_input_press(self, evt: InputPressEvent): if evt.action_id == ACT_BOX_CLICK: self._on_box_click() evt.Skip() def _on_box_click(self): pass
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\operations\base\operation_ui.py
import pickle from typing import Any, TYPE_CHECKING, Union, Tuple import os import wx import weakref import warnings from amulet_map_editor.programs.edit.api.edit_canvas_container import ( EditCanvasContainer, ) from amulet_map_editor.programs.edit.api.ui.canvas_toggle_element import ( CanvasToggleElement, ) if TYPE_CHECKING: from amulet_map_editor.programs.edit.api.canvas import EditCanvas from amulet.api.level import BaseLevel OperationUIType = Union[wx.Window, wx.Sizer, "OperationUI"] class OperationUI(EditCanvasContainer, CanvasToggleElement): """The base class that all operations must inherit from.""" def __init__( self, parent: wx.Window, canvas: "EditCanvas", world: "BaseLevel", options_path: str, ): super().__init__(canvas) self._parent = weakref.ref(parent) self._world = weakref.ref(world) self._options_path = options_path @property def parent(self) -> wx.Window: """The UI element that contains this operation.""" return self._parent() @property def world(self) -> "BaseLevel": """The world to operate on.""" return self._world() @property def wx_add_options(self) -> Tuple[int, ...]: """The options used to put the UI element into a vertical BoxSizer covering the whole canvas. Override if these options do not work for your UI.""" if isinstance(self, wx.Window): return () elif isinstance(self, wx.Sizer): return 1, wx.EXPAND return () def enable(self): """Set the state of the UI for being enabled. Do not bind events to the canvas here because they will get removed. Do this in bind_events. """ pass def bind_events(self): """Bind all required events to the canvas. All events on the canvas will be automatically removed after the UI is disabled. """ pass def disable(self): """Stop the UI and make it safe to be destroyed. Unload any excessive data. May get resumed again with a call to enable. All events bound to the canvas will be automatically removed after this is run. """ if hasattr(self, "unload") and callable(self.unload): warnings.warn( "OperationUI.unload is depreciated and will be removed in the future. Please used OperationUI.disable instead", DeprecationWarning, ) self.unload() def _load_options(self, default=None) -> Any: """Load previously saved options from disk or return the default options.""" try: with open(self._options_path, "rb") as f: return pickle.load(f) except: return default def _save_options(self, options: Any): """Save the given options to disk so that they persist in the next session.""" os.makedirs(os.path.dirname(self._options_path), exist_ok=True) with open(self._options_path, "wb") as f: return pickle.dump(options, f)
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\operations\base\__init__.py
from .operation_ui import OperationUI, OperationUIType from .default_operation_ui import DefaultOperationUI
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\operations\manager\operation_manager.py
import sys from typing import Tuple, Dict, Type from types import ModuleType import os import traceback import pkgutil import importlib import logging from .loader import ( BaseOperationLoader, OperationLoader, UIOperationLoader, ) from .util import STOCK_PLUGINS_DIR, STOCK_PLUGINS_NAME, CUSTOM_PLUGINS_DIR log = logging.getLogger(__name__) class BaseOperationManager: OperationClass: Type[BaseOperationLoader] = None def __init__(self, group_name: str): """Set up an operation manager that handles operations for a set group. :param group_name: The name of the group. This is used to pick the directory. """ # The loaded operations. Stored under their identifier. assert issubclass(self.OperationClass, BaseOperationLoader) self._group_name = group_name self._operations: Dict[str, BaseOperationLoader] = {} self.reload() @property def public_path(self) -> str: return os.path.abspath(os.path.join(CUSTOM_PLUGINS_DIR, self._group_name)) @property def operations(self) -> Tuple[BaseOperationLoader, ...]: return tuple(self._operations.values()) def get_operation(self, operation_id: str): return self._operations[operation_id] def __getitem__(self, operation_id: str): return self._operations[operation_id] def reload(self): """Unload the old operations and reload them all. If new operations are created, load them. If old operations were removed, remove them.""" self._operations.clear() self._load_internal_submodules( os.path.join(STOCK_PLUGINS_DIR, self._group_name), ".".join([STOCK_PLUGINS_NAME, self._group_name]), ) self._load_external_submodules(self.public_path) def _load_internal_submodules(self, package_path: str, package_name: str): """ Load submodules from within a known package. :param package_path: The file path of the package to load submodules from. :param package_name: The python path of the package to load submodules from. """ self._load_submodules(package_path, f"{package_name}.") def _load_external_submodules(self, path: str): """ Load submodules from an external package. Note that the path will be added to the system path. :param path: The path to the directory to find modules in. """ # create the directory os.makedirs(path, exist_ok=True) if path not in sys.path: # The path modules are loaded from should be on the system path sys.path.append(path) self._load_submodules(path) def _load_submodules(self, path: str, package: str = ""): """ Load all operations in a path. You should not use this directly. Use _load_internal_submodules or _load_external_submodules :param path: The path to load modules from. :param package: The package name prefix """ # clean the path path = os.path.abspath(path) for _, module_name, _ in pkgutil.iter_modules([path]): module_name = f"{package}{module_name}" try: mod = importlib.import_module(module_name) mod = importlib.reload(mod) except BaseException: log.warning( f"There was an exception while loading operation {module_name}.\n{traceback.format_exc()}" ) else: if ( os.path.dirname( mod.__path__[0] if hasattr(mod, "__path__") else mod.__file__ ) == path ): # If the loaded module is actually in the path it was loaded from. # There may be cases where the name is shadowed by another module. self._load_module(module_name, mod) else: log.warning( f"Module {module_name} shadows another module. Try using a different module name." ) def _load_module(self, obj_path: str, mod: ModuleType): if hasattr(mod, "export"): export = mod.export if isinstance(export, dict): self._load_operation(obj_path, export) elif isinstance(export, (list, tuple)): for i, export_dict in export: self._load_operation(f"{obj_path}[{i}]", export_dict) else: log.error(f"The format of export in {obj_path} is invalid.") else: log.error(f"export is not present in {obj_path}") def _load_operation(self, identifier: str, export_dict: dict): """Create an instance of a subclass of BaseOperationLoader to load the operation. When finished and the class is valid store it in self._operations :param identifier: A unique identifier for this operation. <path>[0] :param export_dict: The dictionary defining the operation. :return: """ op = self.OperationClass(identifier, export_dict) if op.is_valid: self._operations[op.identifier] = op class OperationManager(BaseOperationManager): OperationClass = OperationLoader """A class to manage a group of function operations that run immediately when called.""" class UIOperationManager(BaseOperationManager): OperationClass = UIOperationLoader """A class to manage a group of UI operations that return a wx UI when called."""
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\operations\manager\util.py
import os from amulet_map_editor.programs.edit.plugins.operations import stock_plugins STOCK_PLUGINS_DIR: str = stock_plugins.__path__[0] STOCK_PLUGINS_NAME: str = stock_plugins.__name__ CUSTOM_PLUGINS_DIR = os.path.join(os.environ["DATA_DIR"], "plugins")
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\operations\manager\__init__.py
from .operation_manager import ( OperationManager, UIOperationManager, BaseOperationManager, ) from .loader import BaseOperationLoader, OperationLoader, UIOperationLoader
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\operations\ui\fixed_pipeline.py
import wx from typing import Callable, Dict, Any, TYPE_CHECKING, Sequence import logging import inspect from amulet_map_editor.api.wx.util.validators import IntValidator from amulet.api.data_types import OperationReturnType from amulet_map_editor.programs.edit.api.operations import DefaultOperationUI if TYPE_CHECKING: from amulet_map_editor.programs.edit.api.canvas import EditCanvas from amulet.api.level import BaseLevel log = logging.getLogger(__name__) FixedOperationType = Callable[ ["BaseLevel", "Dimension", "SelectionGroup", Dict[str, Any]], OperationReturnType ] class FixedFunctionUI(wx.Panel, DefaultOperationUI): def __init__( self, parent: wx.Window, canvas: "EditCanvas", world: "BaseLevel", options_path: str, operation: FixedOperationType, options: Dict[str, Any], ): wx.Panel.__init__(self, parent) DefaultOperationUI.__init__(self, parent, canvas, world, options_path) self._operation = operation self.Hide() self._sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self._sizer) self._options_sizer = wx.BoxSizer(wx.VERTICAL) self._sizer.Add(self._options_sizer) self._run_button = wx.Button(self, label="Run Operation") self._run_button.Bind(wx.EVT_BUTTON, self._run_operation) self._sizer.Add(self._run_button, 0, wx.ALL | wx.ALIGN_CENTRE_HORIZONTAL, 5) self._options: Dict[str, wx.Window] = {} self._create_options(options) self.Layout() self.Show() def _create_options(self, options: Dict[str, Sequence]): create_functions: Dict[str, Callable[[str, Sequence], None]] = { "label": self._create_label, "bool": self._create_bool, "int": self._create_int, "float": self._create_float, "str": self._create_string, "str_choice": self._create_str_choice, "file_open": self._create_file_open_picker, "file_save": self._create_file_save_picker, "directory": self._create_directory_picker, "button": self._create_button, } for option_name, args in options.items(): try: option_type, *args = args if option_type not in create_functions: raise ValueError(f"Invalid option type {option_type}") create_functions[option_type](option_name, *args) except Exception as e: log.exception(e) def _create_label(self, option_name: str): label = wx.StaticText(self, label=option_name) self._options_sizer.Add(label, 0, wx.ALL | wx.ALIGN_CENTRE_HORIZONTAL, 5) def _create_horizontal_options_sizer(self, label) -> wx.BoxSizer: sizer = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, label=label) sizer.Add(label, 0, wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 5) self._options_sizer.Add(sizer, 0, wx.ALL | wx.ALIGN_CENTRE_HORIZONTAL, 5) return sizer def _create_bool(self, option_name: str, value: bool = False): if not isinstance(value, bool): raise TypeError("value must be a bool") sizer = self._create_horizontal_options_sizer(option_name) option = wx.CheckBox(self) sizer.Add(option) option.SetValue(value) self._options[option_name] = option def _create_int( self, option_name: str, initial=0, min_val=-30_000_000, max_val=30_000_000 ): if not ( isinstance(initial, int) and isinstance(min_val, int) and isinstance(max_val, int) ): raise TypeError("Input value must be int") sizer = self._create_horizontal_options_sizer(option_name) option = wx.SpinCtrl( self, min=min(min_val, max_val), max=max(min_val, max_val), initial=initial, ) option.SetValidator(IntValidator()) sizer.Add(option) self._options[option_name] = option def _create_float( self, option_name: str, initial=0, min_val=-30_000_000, max_val=30_000_000 ): if not ( isinstance(initial, (int, float)) and isinstance(min_val, (int, float)) and isinstance(max_val, (int, float)) ): raise TypeError("Input value must be int or float") sizer = self._create_horizontal_options_sizer(option_name) option = wx.SpinCtrlDouble( self, min=min(min_val, max_val), max=max(min_val, max_val), initial=initial, ) sizer.Add(option) self._options[option_name] = option def _create_string(self, option_name: str, value: str = ""): if not isinstance(value, str): raise TypeError("value must be a string") sizer = self._create_horizontal_options_sizer(option_name) option = wx.TextCtrl(self) sizer.Add(option) option.SetValue(value) self._options[option_name] = option def _create_str_choice(self, option_name: str, *choices: str): if not (choices and all(isinstance(o, str) for o in choices)): return sizer = self._create_horizontal_options_sizer(option_name) option = wx.Choice(self, choices=choices) option.SetSelection(0) sizer.Add(option) self._options[option_name] = option def _create_file_picker(self, option_name: str, path: str, mode): if not isinstance(path, str): raise TypeError("path must be a string") sizer = self._create_horizontal_options_sizer(option_name) option = wx.FilePickerCtrl(self, path=path, style=mode | wx.FLP_USE_TEXTCTRL) sizer.Add(option) self._options[option_name] = option def _create_file_save_picker(self, option_name: str, path: str = ""): self._create_file_picker(option_name, path, wx.FLP_SAVE) def _create_file_open_picker(self, option_name: str, path: str = ""): self._create_file_picker(option_name, path, wx.FLP_OPEN) def _create_directory_picker(self, option_name: str, path: str = ""): if not isinstance(path, str): raise TypeError("path must be a string") sizer = self._create_horizontal_options_sizer(option_name) option = wx.DirPickerCtrl(self, path=path, style=wx.DIRP_USE_TEXTCTRL) sizer.Add(option) self._options[option_name] = option def _create_button( self, option_name: str, button_name: str = "", callback: Callable[[], Any] = lambda: None, ): if not isinstance(button_name, str): raise TypeError("button_name must be a string") if inspect.signature(callback).parameters: raise TypeError("callback does not take any arguments") button = wx.Button(self, wx.ID_ANY, button_name) button.Bind(wx.EVT_BUTTON, lambda evt: callback()) sizer = self._create_horizontal_options_sizer(option_name) sizer.Add(button) def _get_values(self) -> Dict[str, Any]: options = {} for key, window in self._options.items(): if isinstance( window, ( wx.CheckBox, wx.SpinCtrl, wx.SpinCtrlDouble, wx.TextCtrl, ), ): options[key] = window.GetValue() elif isinstance(window, wx.Choice): options[key] = window.GetString(window.GetSelection()) elif isinstance(window, (wx.FilePickerCtrl, wx.DirPickerCtrl)): options[key] = window.GetPath() return options def _run_operation(self, evt): self.canvas.run_operation( lambda: self._operation( self.world, self.canvas.dimension, self.canvas.selection.selection_group, self._get_values(), ) )
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\operations\ui\simple_operation_panel.py
import wx from typing import TYPE_CHECKING from amulet.api.selection import SelectionGroup from amulet.api.data_types import Dimension, OperationReturnType from amulet_map_editor.programs.edit.api.operations import DefaultOperationUI if TYPE_CHECKING: from amulet.api.level import BaseLevel from amulet_map_editor.programs.edit.api.canvas import EditCanvas class SimpleOperationPanel(wx.Panel, DefaultOperationUI): def __init__( self, parent: wx.Window, canvas: "EditCanvas", world: "BaseLevel", options_path: str, ): wx.Panel.__init__(self, parent) DefaultOperationUI.__init__(self, parent, canvas, world, options_path) self._sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self._sizer) def _add_run_button(self, label="Run Operation"): self._run_button = wx.Button(self, label=label) self._run_button.Bind(wx.EVT_BUTTON, self._run_operation) self._sizer.Add(self._run_button, 0, wx.ALL | wx.ALIGN_CENTRE_HORIZONTAL, 5) self.Layout() def _run_operation(self, _): self.canvas.run_operation( lambda: self._operation( self.world, self.canvas.dimension, self.canvas.selection.selection_group ) ) def _operation( self, world: "BaseLevel", dimension: Dimension, selection: SelectionGroup ) -> OperationReturnType: raise NotImplementedError
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\operations\ui\__init__.py
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\operations\manager\loader\base_operation_loader.py
import logging log = logging.getLogger(__name__) class BaseOperationLoader: """A class to load and wrap an operation""" def __init__(self, identifier: str, export_dict: dict): """ Set up the OperationLoader. :param identifier: The path to the operation file. This may be a file or directory depending on if it is a module or package. """ self._identifier = identifier self._name = "" self._is_valid = False self._load(export_dict) def _load(self, export_dict: dict): """load the operation.""" if not isinstance(export_dict, dict): log.error(f"The export for {self.identifier} is not a dictionary.") return if "name" in export_dict and isinstance(export_dict["name"], str): self._name = export_dict["name"] self._setup(export_dict) else: log.error(f"Missing or invalid name in {self.identifier}") def _setup(self, export_dict: dict): """Parse the export dictionary and setup as required.""" raise NotImplementedError def __call__(self, *args, **kwargs): """Run the actual operation.""" raise NotImplementedError @property def is_valid(self) -> bool: """Is the module/package a valid operation.""" return self._is_valid @property def identifier(self) -> str: """The identifier for this operation. This is formed of the path and optionally a number if there are multiple operations in the file. """ return self._identifier @property def name(self) -> str: """The name of the operation.""" return self._name
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\operations\manager\loader\operation_loader.py
from typing import Callable, Any, Optional import logging from .base_operation_loader import BaseOperationLoader from amulet.api.level import BaseLevel from amulet.api.data_types import Dimension from amulet.api.selection import SelectionGroup log = logging.getLogger(__name__) class OperationLoader(BaseOperationLoader): def __init__(self, identifier: str, export_dict: dict): self._operation: Optional[ Callable[[BaseLevel, Dimension, SelectionGroup], Any] ] = None super().__init__(identifier, export_dict) def _setup(self, export_dict: dict): """Parse the export dictionary and setup as required.""" if "operation" in export_dict: if callable(export_dict["operation"]): operation = export_dict["operation"] if operation.__code__.co_argcount == 3: self._operation = operation self._is_valid = True else: log.error( f'"operation" function in export must have 3 inputs. {self.identifier}' ) else: log.error( f'"operation" in export must be a callable. {self.identifier}' ) else: log.error(f'"operation" is not present in export. {self.identifier}') def __call__( self, world: BaseLevel, dimension: Dimension, selection: SelectionGroup ): """Run the actual operation.""" self._operation(world, dimension, selection)
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\operations\manager\loader\ui_operation_loader.py
from typing import Callable, Optional, Type, TYPE_CHECKING import inspect import os import struct import hashlib import logging import wx from .base_operation_loader import BaseOperationLoader from amulet.api.level import BaseLevel from amulet_map_editor.programs.edit.api.operations import ( OperationUI, OperationUIType, FixedFunctionUI, ) if TYPE_CHECKING: from amulet_map_editor.programs.edit.api.canvas import EditCanvas from amulet.api.level import BaseLevel log = logging.getLogger(__name__) ValidChrs = set("-_.() abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") class UIOperationLoader(BaseOperationLoader): def __init__(self, identifier: str, export_dict: dict): self._ui: Optional[ Callable[[wx.Window, "EditCanvas", "BaseLevel"], OperationUI] ] = None super().__init__(identifier, export_dict) def _setup(self, export_dict: dict): """Parse the export dictionary and setup as required.""" options_path = os.path.abspath( os.path.join( os.environ["CONFIG_DIR"], "plugins", "edit_plugins", f"""{''.join(c for c in self._name if c in ValidChrs)}_{ struct.unpack( "H", hashlib.sha1( self.identifier.encode('utf-8') ).digest()[:2] )[0] }.config""", # generate a file name that identifiable to the operation but "unique" to the path ) ) if "operation" in export_dict: if inspect.isclass(export_dict["operation"]) and issubclass( export_dict["operation"], (wx.Window, wx.Sizer) ): operation_ui: Type[OperationUI] = export_dict.get("operation", None) if issubclass(operation_ui, OperationUI): self._ui = lambda parent, canvas, world: operation_ui( parent, canvas, world, options_path ) self._is_valid = True else: log.error( f'"operation" must be a subclass of edit.plugins.OperationUI. {self.identifier}' ) elif callable(export_dict["operation"]): operation = export_dict["operation"] if operation.__code__.co_argcount == 4: options = export_dict.get("options", {}) if isinstance(options, dict): self._ui = lambda parent, canvas, world: FixedFunctionUI( parent, canvas, world, options_path, operation, options ) self._is_valid = True else: log.error( f'"operation" in export must be a dictionary if defined. {self.identifier}' ) else: log.error( f'"operation" function in export must have 4 inputs. {self.identifier}' ) else: log.error( f'"operation" in export must be a callable, or a subclass of wx.Window or wx.Sizer. {self.identifier}' ) else: log.error(f'"operation" is not present in export. {self.identifier}') def __call__( self, parent: wx.Window, canvas: "EditCanvas", world: "BaseLevel" ) -> OperationUIType: return self._ui(parent, canvas, world)
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\operations\manager\loader\__init__.py
from .base_operation_loader import BaseOperationLoader from .operation_loader import OperationLoader from .ui_operation_loader import UIOperationLoader
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\ui\select_location\events.py
import wx import math from amulet.api.data_types import BlockCoordinates, FloatTriplet # The location changed _ObjectLocationChangeEventType = wx.NewEventType() EVT_LOCATION_CHANGE = wx.PyEventBinder(_ObjectLocationChangeEventType) class LocationChangeEvent(wx.PyEvent): """Run when the camera has moved or rotated.""" def __init__(self, location: BlockCoordinates): wx.PyEvent.__init__(self, eventType=_ObjectLocationChangeEventType) self._location = location @property def location(self) -> BlockCoordinates: """The location of the object. (x, y, z)""" return self._location # The rotation changed _ObjectRotationChangeEventType = wx.NewEventType() EVT_ROTATION_CHANGE = wx.PyEventBinder(_ObjectRotationChangeEventType) class RotationChangeEvent(wx.PyEvent): """Run when the camera has moved or rotated.""" def __init__(self, rotation: FloatTriplet): wx.PyEvent.__init__(self, eventType=_ObjectRotationChangeEventType) self._rotation = rotation @property def rotation(self) -> FloatTriplet: """The rotation of the object. (x, y, z).""" return self._rotation @property def rotation_radians(self) -> FloatTriplet: """The rotation of the object. (x, y, z).""" return tuple(math.radians(r) for r in self._rotation) # The scale changed _ObjectScaleChangeEventType = wx.NewEventType() EVT_SCALE_CHANGE = wx.PyEventBinder(_ObjectScaleChangeEventType) class ScaleChangeEvent(wx.PyEvent): """Run when the camera has moved or rotated.""" def __init__(self, scale: FloatTriplet): wx.PyEvent.__init__(self, eventType=_ObjectScaleChangeEventType) self._scale = scale @property def scale(self) -> FloatTriplet: """The scale of the object. (x, y, z).""" return self._scale # The location, rotation or scale changed _ObjectTransformEventType = wx.NewEventType() EVT_TRANSFORM_CHANGE = wx.PyEventBinder(_ObjectTransformEventType) class TransformChangeEvent(wx.PyEvent): """Run when the camera has moved or rotated.""" def __init__( self, location: BlockCoordinates, rotation: FloatTriplet, scale: FloatTriplet ): wx.PyEvent.__init__(self, eventType=_ObjectTransformEventType) self._location = location self._rotation = rotation self._scale = scale @property def location(self) -> BlockCoordinates: """The location of the object. (x, y, z)""" return self._location @property def rotation(self) -> FloatTriplet: """The rotation of the object. (x, y, z).""" return self._rotation @property def rotation_radians(self) -> FloatTriplet: """The rotation of the object. (x, y, z).""" return tuple(math.radians(r) for r in self._rotation) @property def scale(self) -> FloatTriplet: """The scale of the object. (x, y, z).""" return self._scale
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\ui\select_location\select_location.py
import wx from typing import Type, Any, Tuple from amulet.api.data_types import BlockCoordinates from amulet_map_editor.api.wx.ui.simple import SimplePanel from amulet_map_editor.api.wx.util.validators import IntValidator from amulet_map_editor.api import config from .events import LocationChangeEvent, TransformChangeEvent class SelectLocationUI(SimplePanel): """A UI element that can be dropped into the EditCanvas and let the user pick a location for a structure. This UI does not allow for rotation.""" def __init__(self, parent: wx.Window): SimplePanel.__init__(self, parent) self._setup_ui() def _add_row(self, label: str, wx_object: Type[wx.Object], **kwargs) -> Any: sizer = wx.BoxSizer(wx.HORIZONTAL) self.add_object(sizer, 0, wx.ALIGN_CENTER_HORIZONTAL) name_text = wx.StaticText(self, label=label) sizer.Add(name_text, flag=wx.CENTER | wx.ALL | wx.EXPAND, border=5) obj = wx_object(self, **kwargs) sizer.Add(obj, flag=wx.CENTER | wx.ALL, border=5) return obj def _setup_ui(self): self._x: wx.SpinCtrl = self._add_row( "x", wx.SpinCtrl, min=-30000000, max=30000000 ) self._y: wx.SpinCtrl = self._add_row( "y", wx.SpinCtrl, min=-30000000, max=30000000 ) self._z: wx.SpinCtrl = self._add_row( "z", wx.SpinCtrl, min=-30000000, max=30000000 ) for ui in (self._x, self._y, self._z): ui.SetValidator(IntValidator()) self._x.Bind(wx.EVT_SPINCTRL, self._on_location_change) self._y.Bind(wx.EVT_SPINCTRL, self._on_location_change) self._z.Bind(wx.EVT_SPINCTRL, self._on_location_change) self._copy_air: wx.CheckBox = self._add_row("Copy Air", wx.CheckBox) copy_air = config.get("edit_select_location", {}).get("copy_air", False) self._copy_air.SetValue(copy_air) self._copy_air.Bind(wx.EVT_CHECKBOX, self._save_config) self._copy_water: wx.CheckBox = self._add_row("Copy Water", wx.CheckBox) copy_water = config.get("edit_select_location", {}).get("copy_water", True) self._copy_water.SetValue(copy_water) self._copy_water.Bind(wx.EVT_CHECKBOX, self._save_config) self._copy_lava: wx.CheckBox = self._add_row("Copy Lava", wx.CheckBox) copy_lava = config.get("edit_select_location", {}).get("copy_lava", True) self._copy_lava.SetValue(copy_lava) self._copy_lava.Bind(wx.EVT_CHECKBOX, self._save_config) @property def location(self) -> BlockCoordinates: return self._x.GetValue(), self._y.GetValue(), self._z.GetValue() @location.setter def location(self, location: Tuple[int, int, int]): x, y, z = location self._x.SetValue(x) self._y.SetValue(y) self._z.SetValue(z) @property def copy_air(self) -> bool: return self._copy_air.GetValue() @copy_air.setter def copy_air(self, copy_air: bool): self._copy_air.SetValue(copy_air) @property def copy_water(self) -> bool: return self._copy_water.GetValue() @copy_water.setter def copy_water(self, copy_water: bool): self._copy_water.SetValue(copy_water) @property def copy_lava(self) -> bool: return self._copy_lava.GetValue() @copy_lava.setter def copy_lava(self, copy_lava: bool): self._copy_lava.SetValue(copy_lava) def _save_config(self, evt): select_config = config.get("edit_select_location", {}) select_config["copy_air"] = self.copy_air select_config["copy_water"] = self.copy_water select_config["copy_lava"] = self.copy_lava config.put("edit_select_location", select_config) def _on_location_change(self, evt): wx.PostEvent(self, LocationChangeEvent(self.location)) self._on_transform_change() def _on_transform_change(self): """The object transform has been changed by the user. Sends""" wx.PostEvent(self, TransformChangeEvent(self.location, (0, 0, 0), (1, 1, 1)))
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\ui\select_location\select_transform.py
import wx import math from amulet.api.data_types import FloatTriplet from .select_location import SelectLocationUI from .events import RotationChangeEvent, ScaleChangeEvent, TransformChangeEvent class SelectTransformUI(SelectLocationUI): """A UI element that can be dropped into the EditCanvas and let the user pick the transform for a structure.""" def _setup_ui(self): super()._setup_ui() # self._sx: wx.SpinCtrl = self._add_row('sx', wx.SpinCtrlDouble, min=-100, max=100, initial=1) # self._sy: wx.SpinCtrl = self._add_row('sy', wx.SpinCtrlDouble, min=-100, max=100, initial=1) # self._sz: wx.SpinCtrl = self._add_row('sz', wx.SpinCtrlDouble, min=-100, max=100, initial=1) # self._sx.Bind(wx.EVT_SPINCTRLDOUBLE, self._on_scale_change) # self._sy.Bind(wx.EVT_SPINCTRLDOUBLE, self._on_scale_change) # self._sz.Bind(wx.EVT_SPINCTRLDOUBLE, self._on_scale_change) self._rx: wx.SpinCtrl = self._add_row( "rx", wx.SpinCtrlDouble, min=-30000000, max=30000000, inc=90, style=wx.SP_ARROW_KEYS | wx.SP_WRAP, ) self._ry: wx.SpinCtrl = self._add_row( "ry", wx.SpinCtrlDouble, min=-30000000, max=30000000, inc=90, style=wx.SP_ARROW_KEYS | wx.SP_WRAP, ) self._rz: wx.SpinCtrl = self._add_row( "rz", wx.SpinCtrlDouble, min=-30000000, max=30000000, inc=90, style=wx.SP_ARROW_KEYS | wx.SP_WRAP, ) self._rx.Bind(wx.EVT_SPINCTRLDOUBLE, self._on_rotation_change) self._ry.Bind(wx.EVT_SPINCTRLDOUBLE, self._on_rotation_change) self._rz.Bind(wx.EVT_SPINCTRLDOUBLE, self._on_rotation_change) @property def scale(self) -> FloatTriplet: return 1, 1, 1 # return self._sx.GetValue(), self._sy.GetValue(), self._sz.GetValue() @property def rotation(self) -> FloatTriplet: return self._rx.GetValue(), self._ry.GetValue(), self._rz.GetValue() @property def rotation_radians(self) -> FloatTriplet: """The rotation of the object. (x, y, z).""" return tuple(math.radians(r) for r in self.rotation) def _on_rotation_change(self, evt): wx.PostEvent(self, RotationChangeEvent(self.rotation)) self._on_transform_change() def _on_scale_change(self, evt): for ctrl in (self._rx, self._ry, self._rz): ctrl.SetValue( round((ctrl.GetValue() % 360) / 90) * 90 ) # TODO: change this if smaller increments are allowed wx.PostEvent(self, ScaleChangeEvent(self.scale)) self._on_transform_change() def _on_transform_change(self): wx.PostEvent( self, TransformChangeEvent(self.location, self.rotation, self.scale) )
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\ui\select_location\__init__.py
from .select_location import SelectLocationUI from .events import ( LocationChangeEvent, EVT_LOCATION_CHANGE, RotationChangeEvent, EVT_ROTATION_CHANGE, ScaleChangeEvent, EVT_SCALE_CHANGE, TransformChangeEvent, EVT_TRANSFORM_CHANGE, ) from .select_transform import SelectTransformUI
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\ui\tool\base_operation_choice.py
import wx from typing import TYPE_CHECKING, Optional import traceback import logging import os import sys import subprocess from amulet_map_editor.api import image from amulet_map_editor.api.wx.ui.simple import SimpleChoiceAny from amulet_map_editor.api.wx.ui.traceback_dialog import TracebackDialog from amulet_map_editor.programs.edit.api.operations import OperationUIType from amulet_map_editor.programs.edit.api.operations.manager import UIOperationManager from .base_tool_ui import BaseToolUI if TYPE_CHECKING: from amulet_map_editor.programs.edit.api.canvas import EditCanvas log = logging.getLogger(__name__) class BaseOperationChoiceToolUI(wx.BoxSizer, BaseToolUI): OperationGroupName = None _active_operation: Optional[OperationUIType] ShowOpenFolder = True def __init__(self, canvas: "EditCanvas"): wx.BoxSizer.__init__(self, wx.VERTICAL) BaseToolUI.__init__(self, canvas) self._active_operation: Optional[OperationUIType] = None self._last_active_operation_id: Optional[str] = None horizontal_sizer = wx.BoxSizer(wx.HORIZONTAL) assert isinstance( self.OperationGroupName, str ), "OperationGroupName has not been set or is not a string." # The operation selection self._operation_choice = SimpleChoiceAny(self.canvas) horizontal_sizer.Add(self._operation_choice) self._operations = UIOperationManager(self.OperationGroupName) self._operation_choice.SetItems( {op.identifier: op.name for op in self._operations.operations} ) self._operation_choice.Bind(wx.EVT_CHOICE, self._on_operation_change) # The reload button self._reload_operation = wx.BitmapButton( self.canvas, bitmap=image.REFRESH_ICON.bitmap(16, 16) ) self._reload_operation.SetToolTip("Reload Operations") horizontal_sizer.Add(self._reload_operation) self._reload_operation.Bind(wx.EVT_BUTTON, self._on_reload_operations) # The open folder button if self.ShowOpenFolder: self._open_folder = wx.BitmapButton( self.canvas, bitmap=image.TABLERICONS.folder.bitmap(16, 16) ) self._open_folder.SetToolTip("Open Plugin Folder") horizontal_sizer.Add(self._open_folder) self._open_folder.Bind(wx.EVT_BUTTON, self._on_open_folder) self.Add(horizontal_sizer) self._operation_sizer = wx.BoxSizer(wx.VERTICAL) self.Add(self._operation_sizer, 1, wx.EXPAND) @property def name(self) -> str: """The name of the group of operations.""" raise NotImplementedError @property def active_operation_id(self) -> str: """The identifier of the operation selected by the choice input. Note if in the process of changing this may be different to self._active_operation. """ return self._operation_choice.GetCurrentObject() def _on_operation_change(self, evt): """Run when the operation selection changes.""" if ( self.active_operation_id and self._last_active_operation_id != self.active_operation_id ): self._setup_operation() self.canvas.reset_bound_events() evt.Skip() def _setup_operation(self): """Remove the old operation and create the UI for the new operation.""" operation_path = self.active_operation_id if operation_path: # only reload the operation if the operation = self._operations[operation_path] if self._active_operation is not None: self._active_operation.disable() self._operation_sizer.Clear(delete_windows=True) try: self._active_operation = operation( self.canvas, self.canvas, self.canvas.world ) self._operation_sizer.Add( self._active_operation, *self._active_operation.wx_add_options ) self._active_operation.enable() except Exception as e: # If something went wrong clear the created UI self._active_operation = None self._operation_sizer.Clear(delete_windows=True) for window in self.canvas.GetChildren(): window: wx.Window # remove orphaned windows. # If the Sizer.Add method was not run it will not be in self._operation_sizer if window.GetContainingSizer() is None: window.Destroy() log.error("Error loading Operation UI.", exc_info=True) dialog = TracebackDialog( self.canvas, "Error loading Operation UI.", str(e), traceback.format_exc(), ) dialog.ShowModal() dialog.Destroy() finally: self._last_active_operation_id = operation.identifier self.Layout() def bind_events(self): if self._active_operation is not None: self._active_operation.bind_events() def enable(self): if self._active_operation is None: self._setup_operation() else: self._active_operation.enable() def disable(self): if self._active_operation is not None: self._active_operation.disable() def _on_reload_operations(self, evt): """Run when the button is pressed to reload the operations.""" self.reload_operations() def reload_operations(self): """Reload all operations and repopulate the UI.""" # store the id of the old operation operation_id = self.active_operation_id # reload the operations self._operations.reload() # repopulate the selection self._operation_choice.SetItems( {op.identifier: op.name for op in self._operations.operations} ) if operation_id: identifiers = self._operation_choice.values if identifiers: if operation_id in identifiers: self._operation_choice.SetSelection(identifiers.index(operation_id)) else: log.info(f"Operation {operation_id} was not found.") self._operation_choice.SetSelection(0) else: log.error("No operations found. Something has gone wrong.") self._setup_operation() self.canvas.reset_bound_events() def _on_open_folder(self, evt): path = self._operations.public_path if not os.path.exists(path): os.makedirs(path) if sys.platform == "win32": os.startfile(path) else: opener = "open" if sys.platform == "darwin" else "xdg-open" subprocess.call([opener, path])
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\ui\tool\base_tool_ui.py
import wx from typing import Union, Any from amulet_map_editor.programs.edit.api.edit_canvas_container import ( EditCanvasContainer, ) from ..canvas_toggle_element import CanvasToggleElement BaseToolUIType = Union[wx.Window, wx.Sizer, "BaseToolUI"] class BaseToolUI(EditCanvasContainer, CanvasToggleElement): """The abstract base class for all tools that are to be loaded into the canvas.""" @property def name(self) -> str: """The name of the tool.""" raise NotImplementedError def enable(self): """Set the state of the tool for being enabled. Do not bind events to the canvas here because they will get removed. Do this in bind_events. """ pass def bind_events(self): """Bind all required events to the canvas. All events on the canvas will be automatically removed after the tool is disabled. """ pass def set_state(self, state: Any): """ Set any state data. In some cases one tool might bounce to another and want to do more than just starting it. This will get called after enabling the tool. :param state: The state to set. Validate that this data is correct because it may come from anywhere. """ pass def disable(self): """Stop the tool. Unload any excessive data. May get resumed again with a call to enable. All events bound to the canvas will be automatically removed after this is run. """ pass
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\ui\tool\default_base_tool_ui.py
import logging import wx from typing import TYPE_CHECKING from OpenGL.GL import ( glClear, GL_DEPTH_BUFFER_BIT, ) import traceback import os import amulet from amulet.api.errors import LoaderNoneMatched from amulet_map_editor.api.wx.ui.traceback_dialog import TracebackDialog from amulet_map_editor.api.opengl.camera import Projection from .base_tool_ui import BaseToolUI from amulet_map_editor.programs.edit.api.events import EVT_DRAW from amulet_map_editor.programs.edit.api.behaviour import CameraBehaviour if TYPE_CHECKING: from amulet_map_editor.programs.edit.api.canvas import EditCanvas log = logging.getLogger(__name__) class DefaultBaseToolUI(BaseToolUI): """A base class for tools that adds a render loop, camera behaviour and file dropping logic.""" def __init__(self, canvas: "EditCanvas"): super().__init__(canvas) self._camera_behaviour = CameraBehaviour(self.canvas) @property def name(self) -> str: """The name of the tool.""" raise NotImplementedError def enable(self): """Set the state of the tool for being enabled.""" self.canvas.camera.projection_mode = Projection.PERSPECTIVE def bind_events(self): """Bind all required events to the canvas. All events on the canvas will be automatically removed after the tool is disabled. """ self.canvas.Bind(EVT_DRAW, self._on_draw) self.canvas.SetDropTarget(None) # fixes #239 self.canvas.DragAcceptFiles(True) self.canvas.Bind(wx.EVT_DROP_FILES, self._on_drop_files) self._camera_behaviour.bind_events() def _on_draw(self, evt): """The render loop for this tool.""" self.canvas.renderer.start_draw() if self.canvas.camera.projection_mode == Projection.PERSPECTIVE: self.canvas.renderer.draw_sky_box() glClear(GL_DEPTH_BUFFER_BIT) self.canvas.renderer.draw_level() self.canvas.renderer.end_draw() def _on_drop_files(self, evt: wx.DropFilesEvent): """Logic to run when a file is dropped into the canvas.""" paths = evt.GetFiles() if paths: pathname = paths[0] if os.path.isfile(pathname): # TODO: if importing worlds get supported fix this try: level = amulet.load_level(pathname) except LoaderNoneMatched: msg = f"Could not find a matching loader for {pathname}." wx.MessageBox(msg) log.error(msg) except Exception as e: log.error(f"Could not open {pathname}.", exc_info=True) dialog = TracebackDialog( self.canvas, f"Could not open {pathname}.", str(e), traceback.format_exc(), ) dialog.ShowModal() dialog.Destroy() else: self.canvas.paste(level, level.dimensions[0]) evt.Skip()
Amulet-Map-Editor
amulet_map_editor\programs\edit\api\ui\tool\__init__.py
from .base_operation_choice import BaseOperationChoiceToolUI from .base_tool_ui import BaseToolUI from .default_base_tool_ui import DefaultBaseToolUI
Amulet-Map-Editor
amulet_map_editor\programs\edit\plugins\operations\__init__.py
Amulet-Map-Editor
amulet_map_editor\programs\edit\plugins\tools\chunk.py
from typing import TYPE_CHECKING, Dict, Tuple, Optional import wx from OpenGL.GL import ( glClear, GL_DEPTH_BUFFER_BIT, GL_DEPTH_TEST, glEnable, glDisable, glGetBoolean, ) from amulet_map_editor import lang from amulet_map_editor.api.opengl.camera import Projection, EVT_CAMERA_MOVED from amulet_map_editor.programs.edit.api.ui.tool import DefaultBaseToolUI from amulet_map_editor.programs.edit.api.behaviour import ChunkSelectionBehaviour from amulet.operations.delete_chunk import delete_chunk from amulet.api.data_types import Dimension from amulet.api.level import BaseLevel from amulet.api.selection import SelectionGroup from amulet.api.chunk import Chunk from amulet_map_editor.programs.edit.plugins.operations.stock_plugins.internal_operations.prune_chunks import ( prune_chunks, ) if TYPE_CHECKING: from amulet_map_editor.programs.edit.api.canvas import EditCanvas class ChunkTool(wx.BoxSizer, DefaultBaseToolUI): def __init__(self, canvas: "EditCanvas"): wx.BoxSizer.__init__(self, wx.HORIZONTAL) DefaultBaseToolUI.__init__(self, canvas) self._selection = ChunkSelectionBehaviour(self.canvas) self._button_panel = wx.Panel(canvas) button_sizer = wx.BoxSizer(wx.VERTICAL) self._button_panel.SetSizer(button_sizer) y_sizer = wx.FlexGridSizer(2, 5, 5) button_sizer.Add(y_sizer, flag=wx.ALL, border=5) min_y_label = wx.StaticText( self._button_panel, label=lang.get("program_3d_edit.chunk_tool.min_y") ) y_sizer.Add(min_y_label, flag=wx.ALIGN_CENTER) self._min_y = wx.SpinCtrl( self._button_panel, min=-30_000_000, max=30_000_000, initial=256, ) self._min_y.SetToolTip(lang.get("program_3d_edit.chunk_tool.min_y_tooltip")) y_sizer.Add(self._min_y, flag=wx.ALIGN_CENTER) self._min_y.Bind(wx.EVT_SPINCTRL, self._on_update_clipping) max_y_label = wx.StaticText( self._button_panel, label=lang.get("program_3d_edit.chunk_tool.max_y") ) y_sizer.Add(max_y_label, flag=wx.ALIGN_CENTER) self._max_y = wx.SpinCtrl( self._button_panel, min=-30_000_000, max=30_000_000, initial=0, ) self._max_y.SetToolTip(lang.get("program_3d_edit.chunk_tool.max_y_tooltip")) y_sizer.Add(self._max_y, flag=wx.ALIGN_CENTER) self._max_y.Bind(wx.EVT_SPINCTRL, self._on_update_clipping) self._dimensions: Dict[Dimension, Tuple[int, int]] = {} create_button = wx.Button( self._button_panel, label=lang.get("program_3d_edit.chunk_tool.create_chunks"), ) create_button.SetToolTip( lang.get("program_3d_edit.chunk_tool.create_chunks_tooltip") ) button_sizer.Add( create_button, 0, wx.LEFT | wx.BOTTOM | wx.RIGHT | wx.EXPAND, 5 ) create_button.Bind(wx.EVT_BUTTON, self._create_chunks) delete_button = wx.Button( self._button_panel, label=lang.get("program_3d_edit.chunk_tool.delete_chunks"), ) delete_button.SetToolTip( lang.get("program_3d_edit.chunk_tool.delete_chunks_tooltip") ) button_sizer.Add( delete_button, 0, wx.LEFT | wx.BOTTOM | wx.RIGHT | wx.EXPAND, 5 ) delete_button.Bind(wx.EVT_BUTTON, self._delete_chunks) prune_button = wx.Button( self._button_panel, label=lang.get("program_3d_edit.chunk_tool.prune_chunks"), ) prune_button.SetToolTip( lang.get("program_3d_edit.chunk_tool.prune_chunks_tooltip") ) button_sizer.Add(prune_button, 0, wx.LEFT | wx.BOTTOM | wx.RIGHT | wx.EXPAND, 5) prune_button.Bind(wx.EVT_BUTTON, self._prune_chunks) self.Add(self._button_panel, 0, wx.ALIGN_CENTER_VERTICAL) @property def name(self) -> str: return "Chunk" def bind_events(self): super().bind_events() self._selection.bind_events() self.canvas.Bind(EVT_CAMERA_MOVED, self._on_update_clipping) def enable(self): self.Layout() self.canvas.camera.projection_mode = Projection.TOP_DOWN self._selection.enable() self._update_clipping() dimension = self.canvas.dimension if dimension not in self._dimensions: self._dimensions[dimension] = ( min( 30_000_000, max(-30_000_000, self.canvas.world.bounds(dimension).min[1]), ), min( 30_000_000, max(-30_000_000, self.canvas.world.bounds(dimension).max[1]), ), ) miny, maxy = self._dimensions[dimension] self._min_y.SetValue(miny) self._max_y.SetValue(maxy) self._update_clipping() def disable(self): super().disable() self.canvas.camera.orthographic_clipping = -(10**5), 10**5 def _on_update_clipping(self, evt): self._update_clipping() evt.Skip() def _update_clipping(self): y = self.canvas.camera.location[1] self.canvas.camera.orthographic_clipping = ( y - self._max_y.GetValue() - 1, y - self._min_y.GetValue() + 1, ) def _ask_delete_chunks(self) -> Optional[bool]: class DeleteChunksDialog(wx.Dialog): def __init__(self, *args, **kwds): kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_DIALOG_STYLE wx.Dialog.__init__(self, *args, **kwds) self.SetTitle("Do you want to load the original chunk state?") sizer_1 = wx.BoxSizer(wx.VERTICAL) label_1 = wx.StaticText( self, wx.ID_ANY, "Do you want to load the original chunk state?\n\n" 'Clicking "Yes" will allow you to undo this operation but the operation will take a while to process.\n\n' 'Clicking "No" will mean this operation cannot be undone.\n\n' "Changes will not be made to the world until you save so closing before saving will not actually delete the chunks.", style=wx.ALIGN_CENTER_HORIZONTAL, ) label_1.Wrap(500) sizer_1.Add(label_1, 0, wx.ALL, 5) sizer_2 = wx.StdDialogButtonSizer() sizer_1.Add(sizer_2, 0, wx.ALIGN_RIGHT | wx.ALL, 4) self.button_YES = wx.Button(self, wx.ID_YES, "") self.button_YES.SetDefault() sizer_2.AddButton(self.button_YES) self.button_NO = wx.Button(self, wx.ID_NO, "") self.button_NO.Bind(wx.EVT_BUTTON, self._on_no) sizer_2.AddButton(self.button_NO) self.button_CANCEL = wx.Button(self, wx.ID_CANCEL, "") sizer_2.AddButton(self.button_CANCEL) sizer_2.Realize() self.SetSizer(sizer_1) sizer_1.Fit(self) self.SetAffirmativeId(self.button_YES.GetId()) self.SetEscapeId(self.button_CANCEL.GetId()) self.Layout() def _on_no(self, evt): self.EndModal(wx.ID_NO) d = DeleteChunksDialog(self.canvas) response = d.ShowModal() if response == wx.ID_YES: return True elif response == wx.ID_NO: return False return None def _create_chunks(self, evt): def create_chunks( world: BaseLevel, dimension: Dimension, selection: SelectionGroup, ): for cx, cz in selection.chunk_locations(): if not world.has_chunk(cx, cz, dimension): world.put_chunk(Chunk(cx, cz), dimension) self.canvas.run_operation( lambda: create_chunks( self.canvas.world, self.canvas.dimension, self.canvas.selection.selection_group, ) ) def _delete_chunks(self, evt): load_original = self._ask_delete_chunks() if load_original is not None: self.canvas.run_operation( lambda: delete_chunk( self.canvas.world, self.canvas.dimension, self.canvas.selection.selection_group, load_original, ) ) def _prune_chunks(self, evt): load_original = self._ask_delete_chunks() if load_original is not None: self.canvas.run_operation( lambda: prune_chunks( self.canvas.world, self.canvas.dimension, self.canvas.selection.selection_group, load_original, ) ) def _on_draw(self, evt): self.canvas.renderer.start_draw() if self.canvas.camera.projection_mode == Projection.PERSPECTIVE: self.canvas.renderer.draw_sky_box() glClear(GL_DEPTH_BUFFER_BIT) self.canvas.renderer.draw_level() if self.canvas.camera.projection_mode == Projection.PERSPECTIVE: self._selection.draw() else: depth_state = glGetBoolean(GL_DEPTH_TEST) if depth_state: glDisable(GL_DEPTH_TEST) clip = self.canvas.camera.orthographic_clipping self.canvas.camera.orthographic_clipping = -(10**5), 10**5 self._selection.draw() self.canvas.camera.orthographic_clipping = clip if depth_state: glEnable(GL_DEPTH_TEST) self.canvas.renderer.end_draw()