Skip to content

Commit

Permalink
Fixed mypy issues
Browse files Browse the repository at this point in the history
Replaced transparency int with an int enum.
Added type hints.
Fixed code highlighted by mypy
  • Loading branch information
gentlegiantJGC committed May 24, 2024
1 parent e3b4316 commit 3fc16ed
Show file tree
Hide file tree
Showing 27 changed files with 206 additions and 142 deletions.
2 changes: 1 addition & 1 deletion minecraft_model_reader/api/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
try:
from amulet.api.block import Block
from amulet.api.block import Block # type: ignore
except ModuleNotFoundError:
from minecraft_model_reader.api.amulet.block import Block

Expand Down
13 changes: 10 additions & 3 deletions minecraft_model_reader/api/mesh/block/block_mesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from collections.abc import Iterable
import numpy
import itertools
from enum import IntEnum

from minecraft_model_reader.api.mesh.util import rotate_3d

Expand Down Expand Up @@ -33,6 +34,12 @@ def _create_cull_map() -> dict[tuple[int, int], dict[Optional[str], Optional[str
cull_remap_all = _create_cull_map()


class Transparency(IntEnum):
FullOpaque = 0 # the block is a full block with opaque textures
FullTranslucent = 1 # the block is a full block with transparent/translucent textures
Partial = 2 # the block is not a full block


class BlockMesh:
"""Class for storing model data"""

Expand All @@ -46,7 +53,7 @@ def merge(cls, models: Iterable[BlockMesh]) -> BlockMesh:
tint_verts_src: dict[Optional[str], list[numpy.ndarray]] = {side: [] for side in FACE_KEYS}
faces_src: dict[Optional[str], list[numpy.ndarray]] = {side: [] for side in FACE_KEYS}
texture_indexes_src: dict[Optional[str], list[numpy.ndarray]] = {side: [] for side in FACE_KEYS}
transparent = 2
transparent: Transparency = Transparency.Partial

cull_dir: Optional[str]
for temp_model in models:
Expand Down Expand Up @@ -116,7 +123,7 @@ def __init__(
faces: dict[Optional[str], numpy.ndarray],
texture_index: dict[Optional[str], numpy.ndarray],
textures: tuple[str, ...],
transparency: int,
transparency: Transparency,
):
"""
Expand Down Expand Up @@ -273,7 +280,7 @@ def is_opaque(self) -> bool:
return not self._transparency

@property
def is_transparent(self) -> int:
def is_transparent(self) -> Transparency:
"""
The transparency mode of the block
0 - the block is a full block with opaque textures
Expand Down
12 changes: 6 additions & 6 deletions minecraft_model_reader/api/mesh/block/cube.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import numpy
import itertools

from minecraft_model_reader.api.mesh.block.block_mesh import FACE_KEYS, BlockMesh
from minecraft_model_reader.api.mesh.block.block_mesh import BlockMesh, Transparency

BoundsType = tuple[tuple[float, float], tuple[float, float], tuple[float, float]]
TextureUVType = tuple[
Expand Down Expand Up @@ -70,7 +70,7 @@ def get_cube(
east: str,
south: str,
west: str,
transparency=0,
transparency: Transparency = Transparency.FullOpaque,
tint: tuple[int, int, int] = (1, 1, 1),
bounds: BoundsType = ((0, 1), (0, 1), (0, 1)),
texture_uv: TextureUVType = ((0, 0, 1, 1),) * 6,
Expand All @@ -82,7 +82,7 @@ def get_cube(
False,
False,
),
):
) -> BlockMesh:
box_coordinates = numpy.array(list(itertools.product(*bounds)))
_texture_uv: dict[Optional[str], numpy.ndarray] = {
face: numpy.array(texture_uv[i], float) for i, face in enumerate(cube_face_lut)
Expand All @@ -101,10 +101,10 @@ def get_cube(
_tint_verts[_face_dir] = numpy.full((4, 3), tint, dtype=float).ravel()
_tri_faces[_face_dir] = tri_face

texture_paths, texture_index = numpy.unique(
texture_paths_arr, texture_index = numpy.unique(
(down, up, north, east, south, west), return_inverse=True
)
texture_paths = tuple(texture_paths)
texture_paths = tuple(texture_paths_arr)
_tri_texture_index: dict[Optional[str], numpy.ndarray] = {
side: numpy.full(2, texture_index[side_index], dtype=numpy.uint32)
for side_index, side in enumerate(cube_face_lut)
Expand Down Expand Up @@ -143,7 +143,7 @@ def get_unit_cube(
east: str,
south: str,
west: str,
transparency: int = 0,
transparency: Transparency = Transparency.FullOpaque,
tint: tuple[int, int, int] = (1, 1, 1),
) -> BlockMesh:
return get_cube(down, up, north, east, south, west, transparency, tint)
10 changes: 5 additions & 5 deletions minecraft_model_reader/api/resource_pack/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from .unknown_resource_pack import UnknownResourcePack


def load_resource_pack(resource_pack_path: str):
def load_resource_pack(resource_pack_path: str) -> BaseResourcePack:
if JavaResourcePack.is_valid(resource_pack_path):
return JavaResourcePack(resource_pack_path)
elif BedrockResourcePack.is_valid(resource_pack_path):
Expand All @@ -25,9 +25,9 @@ def load_resource_pack(resource_pack_path: str):


def load_resource_pack_manager(
resource_packs: Iterable[Union[str, BaseResourcePack]], load=True
resource_packs: Iterable[Union[str, BaseResourcePack]], load: bool = True
) -> BaseResourcePackManager:
resource_packs_out = []
resource_packs_out: list[BaseResourcePack] = []
for resource_pack in resource_packs:
if isinstance(resource_pack, str):
resource_pack = load_resource_pack(resource_pack)
Expand All @@ -44,9 +44,9 @@ def load_resource_pack_manager(
resource_packs = resource_packs_out
if resource_packs:
if isinstance(resource_packs[0], JavaResourcePack):
return JavaResourcePackManager(resource_packs, load)
return JavaResourcePackManager([pack for pack in resource_packs if isinstance(pack, JavaResourcePack)], load)
elif isinstance(resource_packs[0], BedrockResourcePack):
return BedrockResourcePackManager(resource_packs, load)
return BedrockResourcePackManager([pack for pack in resource_packs if isinstance(pack, BedrockResourcePack)], load)

raise NotImplementedError
# return UnknownResourcePackManager()
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from typing import Generator, Optional
import os
from typing import Optional, Iterator, TypeVar, Generic
import json
import copy

Expand All @@ -8,37 +7,39 @@
from minecraft_model_reader.api.image import missing_no_path
from minecraft_model_reader.api.mesh.block.missing_block import get_missing_block

PackT = TypeVar('PackT', bound=BaseResourcePack)

class BaseResourcePackManager:

class BaseResourcePackManager(Generic[PackT]):
"""The base class that all resource pack managers must inherit from. Defines the base api."""

def __init__(self):
self._packs: list[BaseResourcePack] = []
self._missing_block = None
self._texture_is_transparent = {}
def __init__(self) -> None:
self._packs: list[PackT] = []
self._missing_block: Optional[BlockMesh] = None
self._texture_is_transparent: dict[str, tuple[float, bool]] = {}
self._cached_models: dict[Block, BlockMesh] = {}

@property
def pack_paths(self):
def pack_paths(self) -> list[str]:
return [pack.root_dir for pack in self._packs]

def _unload(self):
def _unload(self) -> None:
"""Clear all loaded resources."""
self._texture_is_transparent.clear()
self._cached_models.clear()

def _load_transparency_cache(self, path: str):
def _load_transparency_cache(self, path: str) -> None:
try:
with open(path) as f:
self._texture_is_transparent = json.load(f)
except:
pass

def _load_iter(self) -> Generator[float, None, None]:
def _load_iter(self) -> Iterator[float]:
"""Load resources."""
raise NotImplementedError

def reload(self) -> Generator[float, None, None]:
def reload(self) -> Iterator[float]:
"""Unload and reload resources"""
self._unload()
yield from self._load_iter()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import importlib
import pkgutil
import minecraft_model_reader

from .base_blockshape import BaseBlockShape

BlockShapeClasses = {}
BlockShapeClasses: dict[str, BaseBlockShape] = {}
_class_names = set()


def _load_blockshape(module_name: str):
def _load_blockshape(module_name: str) -> None:
blockshape_module = importlib.import_module(module_name)
if hasattr(blockshape_module, "BlockShape"):
blockshape = getattr(blockshape_module, "BlockShape")
Expand All @@ -22,7 +21,7 @@ def _load_blockshape(module_name: str):
BlockShapeClasses[blockshape.blockshape] = blockshape


def _load_blockshapes():
def _load_blockshapes() -> None:
package_prefix = __name__ + "."

for _, name, _ in pkgutil.walk_packages(__path__, package_prefix):
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from minecraft_model_reader.api.mesh.block import BlockMesh
from minecraft_model_reader.api.mesh.block.block_mesh import BlockMesh, Transparency
from minecraft_model_reader.api import Block
from minecraft_model_reader.api.resource_pack.bedrock.blockshapes.base_blockshape import (
BaseBlockShape,
Expand All @@ -21,15 +21,15 @@ def texture_index(self, block: Block, aux_value: int) -> int:
def get_block_model(
self,
block: Block,
up: str,
down: str,
up: str,
north: str,
east: str,
south: str,
west: str,
transparency: tuple[bool, bool, bool, bool, bool, bool],
) -> BlockMesh:
return BlockMesh(3, {}, {}, {}, {}, {}, (), 2)
return BlockMesh(3, {}, {}, {}, {}, {}, (), Transparency.Partial)


BlockShape = Air()
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ def texture_index(self, block: Block, aux_value: int) -> int:
def get_block_model(
self,
block: Block,
up: str,
down: str,
up: str,
north: str,
east: str,
south: str,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@ def bounds(
self, block: Block
) -> tuple[tuple[float, float], tuple[float, float], tuple[float, float]]:
return (
(1 / 16 + block.properties["bite_counter"].py_data * 2 / 16, 15 / 16),
(1 / 16 + block.properties["bite_counter"].py_int * 2 / 16, 15 / 16),
(0, 0.5),
(1 / 16, 15 / 16),
)

def texture_index(self, block: Block, aux_value: int) -> int:
return min(block.properties["bite_counter"].py_data, 1)
bite_counter = block.properties["bite_counter"]
assert isinstance(bite_counter, amulet_nbt.AbstractBaseIntTag)
return min(1, bite_counter.py_int)

@property
def do_not_cull(self) -> tuple[bool, bool, bool, bool, bool, bool]:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Any

from minecraft_model_reader.api.resource_pack.bedrock.blockshapes.partial_block import (
PartialBlock,
)
Expand Down Expand Up @@ -32,7 +34,9 @@ def get_block_model(
south: str,
west: str,
transparency: tuple[bool, bool, bool, bool, bool, bool],
modify_uv=True,
modify_uv: bool = True,
*args: Any,
**kwargs: Any
) -> BlockMesh:
rotation = {2: 2, 3: 0, 4: 1, 5: 3}.get(
block.properties["facing_direction"].py_data, 0
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Any

from minecraft_model_reader.api.resource_pack.bedrock.blockshapes.partial_block import (
PartialBlock,
)
Expand Down Expand Up @@ -36,6 +38,8 @@ def get_block_model(
south: str,
west: str,
transparency: tuple[bool, bool, bool, bool, bool, bool],
*args: Any,
**kwargs: Any
) -> BlockMesh:
return (
super()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import numpy

from minecraft_model_reader.api.mesh.block import BlockMesh
from minecraft_model_reader.api.mesh.block.block_mesh import BlockMesh, Transparency
from minecraft_model_reader.api import Block
from minecraft_model_reader.api.resource_pack.bedrock.blockshapes.base_blockshape import (
BaseBlockShape,
Expand Down Expand Up @@ -179,7 +179,7 @@ def get_block_model(
)
},
(up,),
2,
Transparency.Partial,
)


Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from minecraft_model_reader.api.mesh.block import BlockMesh
from minecraft_model_reader.api.mesh.block.block_mesh import BlockMesh, Transparency
from minecraft_model_reader.api import Block
from minecraft_model_reader.api.mesh.block.cube import get_unit_cube
from minecraft_model_reader.api.resource_pack.bedrock.blockshapes.default import Default
Expand All @@ -20,7 +20,7 @@ def get_block_model(
west: str,
transparency: tuple[bool, bool, bool, bool, bool, bool],
) -> BlockMesh:
return get_unit_cube(down, up, north, east, south, west, int(any(transparency)))
return get_unit_cube(down, up, north, east, south, west, Transparency.FullTranslucent if any(transparency) else Transparency.FullOpaque)


BlockShape = Cube()
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import numpy

from minecraft_model_reader.api.mesh.block import BlockMesh
from minecraft_model_reader.api.mesh.block.block_mesh import BlockMesh, Transparency
from minecraft_model_reader.api import Block
from minecraft_model_reader.api.resource_pack.bedrock.blockshapes.default import Default

Expand Down Expand Up @@ -51,5 +51,5 @@ def get_block_model(
{None: numpy.array([0, 1, 2, 0, 2, 3], numpy.uint32)},
{None: numpy.array([0, 0], numpy.uint32)},
(up,),
2,
Transparency.Partial,
)
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import numpy

from minecraft_model_reader.api.mesh.block import BlockMesh
from minecraft_model_reader.api.mesh.block.block_mesh import BlockMesh, Transparency
from minecraft_model_reader.api import Block
from minecraft_model_reader.api.resource_pack.bedrock.blockshapes.default import Default

Expand Down Expand Up @@ -51,5 +51,5 @@ def get_block_model(
{None: numpy.array([0, 1, 2, 0, 2, 3], numpy.uint32)},
{None: numpy.array([0, 0], numpy.uint32)},
(up,),
2,
Transparency.Partial,
)
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from minecraft_model_reader.api.mesh.block import BlockMesh
from minecraft_model_reader.api.mesh.block.block_mesh import BlockMesh, Transparency
from minecraft_model_reader.api import Block
from minecraft_model_reader.api.mesh.block.cube import get_unit_cube
from minecraft_model_reader.api.resource_pack.bedrock.blockshapes.cube import Cube
Expand All @@ -21,7 +21,7 @@ def get_block_model(
transparency: tuple[bool, bool, bool, bool, bool, bool],
) -> BlockMesh:
return get_unit_cube(
down, up, north, east, south, west, int(any(transparency)), (0, 1, 0)
down, up, north, east, south, west, Transparency.FullTranslucent if any(transparency) else Transparency.FullOpaque, (0, 1, 0)
)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def get_block_model(
south: str,
west: str,
transparency: tuple[bool, bool, bool, bool, bool, bool],
modify_uv=True,
modify_uv: bool = True,
) -> BlockMesh:
rotation = {2: 2, 3: 0, 4: 1, 5: 3}.get(
block.properties["facing_direction"].py_data, 0
Expand Down
Loading

0 comments on commit 3fc16ed

Please sign in to comment.