Skip to content

Commit

Permalink
Fixed problems detected by pylint.
Browse files Browse the repository at this point in the history
  • Loading branch information
Nusiq committed Sep 2, 2023
1 parent 06b8923 commit 1cdd56f
Show file tree
Hide file tree
Showing 18 changed files with 485 additions and 421 deletions.
641 changes: 343 additions & 298 deletions .pylintrc

Large diffs are not rendered by default.

3 changes: 1 addition & 2 deletions mcblend/common_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
as pointers.
'''
from bpy.types import PropertyGroup
from bpy.props import (
CollectionProperty, StringProperty, BoolProperty, IntProperty)
from bpy.props import StringProperty, IntProperty


class MCBLEND_JustName(PropertyGroup):
Expand Down
21 changes: 10 additions & 11 deletions mcblend/operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
import json
from pathlib import Path
from json.decoder import JSONDecodeError
from typing import Any, List, Optional, Dict, Any, Set, TYPE_CHECKING
from typing import List, Optional, Dict, Any, Set, TYPE_CHECKING

import bpy
from bpy.types import Operator, Context, Object
from bpy.types import Operator, Context
from bpy.props import (
StringProperty, FloatProperty, EnumProperty, BoolProperty, IntProperty)
from bpy_extras.io_utils import ExportHelper, ImportHelper
Expand Down Expand Up @@ -91,7 +91,7 @@ def execute(self, context):
finally:
context.scene.frame_set(original_frame)

with open(self.filepath, 'w') as f:
with open(self.filepath, 'w', encoding='utf8') as f:
json.dump(result, f, cls=CompactEncoder)
if warnings_counter > 1:
self.report(
Expand Down Expand Up @@ -153,13 +153,13 @@ def execute(self, context: Context):
old_dict: Optional[Dict] = None
filepath: str = self.filepath # type: ignore
try:
with open(filepath, 'r') as f:
with open(filepath, 'r', encoding='utf8') as f:
old_dict = json.load(f, cls=JSONCDecoder)
except (json.JSONDecodeError, OSError):
pass
animation_dict = export_animation(context, old_dict)
# Save file and finish
with open(filepath, 'w') as f:
with open(filepath, 'w', encoding='utf8') as f:
json.dump(animation_dict, f, cls=CompactEncoder)
self.report({'INFO'}, f'Animation saved in {filepath}.')
return {'FINISHED'}
Expand Down Expand Up @@ -206,8 +206,7 @@ def execute(self, context):
# f"Object: {obj.name}; Frame: 0.")
# return {'FINISHED'}
set_uvs(context)
except NotEnoughTextureSpace as e:
raise e
except NotEnoughTextureSpace:
self.report(
{'ERROR'},
"Not enough texture space to create UV mapping.")
Expand Down Expand Up @@ -389,7 +388,7 @@ class MCBLEND_OT_SeparateMeshCubes(Operator):
Adjusts the rotations of the newly created objects to match the rotations
of the cubes inside of this object.
'''
# pylint: disable=unused-argument, R0201, no-member
# pylint: disable=unused-argument, no-member
bl_idname = "mcblend.separate_mesh_cubes"
bl_label = "Separate and align cubes"
bl_options = {'UNDO'}
Expand Down Expand Up @@ -442,7 +441,7 @@ class MCBLEND_OT_ImportModel(Operator, ImportHelper):

def execute(self, context):
# Save file and finish
with open(self.filepath, 'r') as f:
with open(self.filepath, 'r', encoding='utf8') as f:
data = json.load(f, cls=JSONCDecoder)
try:
warnings = import_model(data, self.geometry_name, context)
Expand Down Expand Up @@ -1119,7 +1118,7 @@ def execute(self, context):
group_id = get_scene_mcblend_active_uv_group(context)
uv_group = get_scene_mcblend_uv_groups(context)[group_id]

with open(self.filepath, 'w') as f:
with open(self.filepath, 'w', encoding='utf8') as f:
json.dump(uv_group.json(), f, cls=CompactEncoder)
self.report({'INFO'}, f'UV group saved in {self.filepath}.')
return {'FINISHED'}
Expand Down Expand Up @@ -1402,7 +1401,7 @@ def execute(self, context) -> Set[str]:
# Save file and finish
try:
filepath: str = self.filepath # type: ignore
with open(filepath, 'r') as f:
with open(filepath, 'r', encoding='utf8') as f:
data = json.load(f, cls=JSONCDecoder)
version = data['version']
if version != 1:
Expand Down
18 changes: 9 additions & 9 deletions mcblend/operator_func/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,17 @@
from __future__ import annotations

from pathlib import Path
import json
from typing import (
Dict, Iterable, List, Literal, Optional, Tuple, cast, TYPE_CHECKING,
Callable)
from dataclasses import dataclass, field
from collections import defaultdict
from .common import ModelOriginType

import bpy
from mathutils import Matrix
from bpy.types import Image, Material, Context, Object
import numpy as np

from .common import ModelOriginType
from .typed_bpy_access import (
get_data_bones, get_objects,
get_context_object, get_scene_mcblend_project,
Expand Down Expand Up @@ -50,8 +48,8 @@
from ..resource_pack_data import MCBLEND_ProjectProperties
from ..object_data import MCBLEND_ObjectProperties
else:
MCBLEND_ProjectProperties = None
MCBLEND_ObjectProperties = None
MCBLEND_ProjectProperties = None # pylint: disable=invalid-name
MCBLEND_ObjectProperties = None # pylint: disable=invalid-name

def export_model(
context: Context) -> Tuple[Dict, Iterable[str]]:
Expand Down Expand Up @@ -460,7 +458,9 @@ def load_rp_to_mcblned(
last_name = name

def unload_rps(context: Context):
# Clear the selection in GUI
'''
Unload resrouce pakcs in GUI.
'''
mcblend_project = get_scene_mcblend_project(context)
mcblend_project = cast(MCBLEND_ProjectProperties, mcblend_project)
mcblend_project.entity_render_controllers.clear()
Expand Down Expand Up @@ -807,7 +807,7 @@ def prepare_physics_simulation(context: Context) -> Dict:
get_objects(context.view_layer).active = armature
bpy.ops.object.posemode_toggle() # Pose mode
bpy.ops.pose.select_all(action='DESELECT')

get_data_bones(armature).active = get_data_bones(
armature)[bone.thisobj_id.bone_name]
# bpy.ops.pose.constraint_add(type='COPY_TRANSFORMS')
Expand Down Expand Up @@ -903,7 +903,7 @@ def merge_models(context: Context) -> None:
arr = np.zeros([image.size[1], image.size[0], 4])
for merger in uv_mergers:
pixels = np.array(get_pixels(merger.base_image))
merger.base_image_size

pixels = pixels.reshape([
merger.base_image_size[1], merger.base_image_size[0], 4
])
Expand Down Expand Up @@ -943,4 +943,4 @@ def merge_models(context: Context) -> None:
material.pattern = '*'
material.material = 'entity_alphatest'
# APPLY THE RENDER CONTROLLER
apply_materials(context)
apply_materials(context)
8 changes: 4 additions & 4 deletions mcblend/operator_func/animation.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
import math # pyright: ignore[reportShadowedImports]
from dataclasses import dataclass, field
from itertools import tee, islice # pyright: ignore[reportShadowedImports]
from decimal import Decimal

import bpy
from bpy.types import Action, Context
from decimal import Decimal

import numpy as np

Expand Down Expand Up @@ -101,7 +101,7 @@ def _get_keyframes(context: Context, prec: int=1) -> List[float]:
actions of the active object. The results are returned as float (allowing
use of the subframes). The precision of the results is limited to the value
specified by the prec argument.
!!! Important note
The precision limitation is applied to avoid very small differences in the
Expand Down Expand Up @@ -134,8 +134,8 @@ def get_action_keyframes(action: Action) -> List[float]:
if obj.animation_data is None:
return []
if obj.animation_data.action is not None:
for kf in get_action_keyframes(obj.animation_data.action):
keyframes.add(round(kf, prec))
for keyframe in get_action_keyframes(obj.animation_data.action):
keyframes.add(round(keyframe, prec))
if obj.animation_data.nla_tracks is None:
return sorted(keyframes)
for nla_track in get_nla_tracks(obj.animation_data):
Expand Down
12 changes: 7 additions & 5 deletions mcblend/operator_func/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@
from mathutils import Vector, Matrix, Euler

from .typed_bpy_access import (
add, decompose, get_children, get_co, get_data, get_data_edges, get_matrix, get_pose_bones, get_scene_mcblend_uv_groups, get_data_bones, get_data_polygons, get_data_vertices,
get_matrix_local, get_matrix_world, get_mcblend, getitem, matmul, matmul_chain, set_co, set_matrix_local, set_matrix_world,
add, decompose, get_children, get_co, get_data, get_data_edges, get_matrix,
get_pose_bones, get_scene_mcblend_uv_groups, get_data_bones,
get_data_polygons, get_data_vertices, get_matrix_local, get_matrix_world,
get_mcblend, getitem, matmul, matmul_chain, set_co, set_matrix_local,
subtract, cross, neg, to_euler)

from .texture_generator import Mask, ColorMask, get_masks_from_side
Expand Down Expand Up @@ -906,8 +908,8 @@ def apply_obj_transform_keep_origin(obj: Object):
rotation and scale but keeps location the same.
'''
# Decompose object transformations
loc, rot, scl = decompose(get_matrix_local(obj))
loc_mat = Matrix.Translation(loc)
_, rot, scl = decompose(get_matrix_local(obj))
# loc_mat = Matrix.Translation(loc)
rot_mat = rot.to_matrix().to_4x4()
scl_mat = matmul_chain(
Matrix.Scale(getitem(scl, 0), 4, Vector([1,0,0])),
Expand Down Expand Up @@ -942,7 +944,7 @@ def fix_cube_rotation(obj: Object):

# The cross product creates the 3rd vector that defines
# the rotated space

w = cross(u, v).normalized()
# Recalculate V to make sure that all of the vectors are at
# the right angle (even though they should be)
Expand Down
30 changes: 22 additions & 8 deletions mcblend/operator_func/db_handler.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,29 @@
'''
The module that defines the classes and functions that are used to interact
with the database while loading data from resource packs.
'''
# pylint: disable=method-cache-max-size-none
from __future__ import annotations

from pathlib import Path
from .sqlite_bedrock_packs import Database
# load_rp
from typing import Optional

# Don't use lru_cache(maxsize=1) sometimes there are more than 1 lists of the
# same type shown in the UI. Just make sure to call cache_clear() when you can.
from functools import cache

from .sqlite_bedrock_packs import Database

@cache
def get_db_handler() -> DbHandler:
'''Singleton for the database handler'''
return DbHandler()

class DbHandler:
'''
A singleton class that is used to interact with the database that loads
and stores the data from resource packs.
'''
def __init__(self):
self.db = Database.create()
self.is_loaded = False
Expand All @@ -26,6 +35,8 @@ def load_db_from_file(self, path: Path):
self.is_loaded = True

def _clear_cache(self):
'''Clears all of the cached values.'''
# pylint: disable=no-member
self.gui_enum_entity_materials.cache_clear()
self.gui_enum_entity_fake_material_patterns.cache_clear()
self.gui_enum_entity_geometries.cache_clear()
Expand All @@ -43,7 +54,7 @@ def _clear_cache(self):
self.gui_enum_attachable_textures_for_fake_rc.cache_clear()
self.list_attachable_render_controllers.cache_clear()
self.list_attachables_with_models_and_rc.cache_clear()

self.list_bone_name_patterns.cache_clear()

def delete_db(self):
Expand Down Expand Up @@ -533,7 +544,7 @@ def gui_enum_attachable_textures(
not_found_counter = 0
for texture_pk, short_name, path in self.db.connection.execute(
query, (rc_pk, attachable_pk)):

if texture_pk is None:
texture_pk = f'not_found_{not_found_counter}'
not_found_counter += 1
Expand Down Expand Up @@ -658,7 +669,7 @@ def list_entity_render_controllers(
loaded last will be used). If a pack has multiple render controllers
with the same identifier (which is not allowed), the last one is used.
'''

# pylint: disable=unnecessary-comprehension
query = '''
SELECT pk, identifier FROM (
SELECT DISTINCT
Expand Down Expand Up @@ -704,7 +715,7 @@ def list_attachable_render_controllers(
loaded last will be used). If a pack has multiple render controllers
with the same identifier (which is not allowed), the last one is used.
'''

# pylint: disable=unnecessary-comprehension
query = '''
SELECT pk, identifier FROM (
SELECT DISTINCT
Expand Down Expand Up @@ -740,6 +751,7 @@ def list_bone_name_patterns(self, render_controller_pk: int) -> list[str]:
Lists all of the distinct bone name patterns from the given
render controller. The result is a string with the bone name pattern.
'''
# pylint: disable=unnecessary-comprehension
query = '''
SELECT DISTINCT boneNamePattern
FROM RenderControllerMaterialsField
Expand All @@ -755,7 +767,7 @@ def list_bone_name_patterns(self, render_controller_pk: int) -> list[str]:
def list_entities_with_models_and_rc(self) -> list[tuple[int, str]]:
'''
Lists all of the all of the entities from database that use geometries
and render_controlelrs fields. There must be at least one
and render_controlelrs fields. There must be at least one
geometry in the database that connects to the geometry field. The
render controller don't have to exist but there must be a render
controller field in the client entity file.
Expand All @@ -767,6 +779,7 @@ def list_entities_with_models_and_rc(self) -> list[tuple[int, str]]:
Results are ordered by identifier
'''
# pylint: disable=unnecessary-comprehension

# DISTINCT in SELECT is needed, because there can be multiple geometry
# or rc fields in one entity
Expand Down Expand Up @@ -794,7 +807,7 @@ def list_entities_with_models_and_rc(self) -> list[tuple[int, str]]:
def list_attachables_with_models_and_rc(self) -> list[tuple[int, str]]:
'''
Lists all of the all of the attachables from database that use
geometries and render_controlelrs fields. There must be at least one
geometries and render_controlelrs fields. There must be at least one
geometry in the database that connects to the geometry field. The
render controller don't have to exist but there must be a render
controller field in the attachable file.
Expand All @@ -806,6 +819,7 @@ def list_attachables_with_models_and_rc(self) -> list[tuple[int, str]]:
Results are ordered by identifier
'''
# pylint: disable=unnecessary-comprehension

# DISTINCT in SELECT is needed, because there can be multiple geometry
# or rc fields in one attachable
Expand Down
11 changes: 5 additions & 6 deletions mcblend/operator_func/importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@
import bpy

from .typed_bpy_access import (
add, get_data_edit_bones, get_data_meshes, get_data_uv_layers, get_data_vertices, get_head,
get_loop_indices, get_matrix_world, get_data, get_objects, get_rotation_euler, get_tail, get_uv_layers,
matmul, set_matrix, set_matrix_parent_inverse, set_matrix_world,
get_data_edit_bones, get_data_meshes, get_data_uv_layers,
get_data_vertices, get_head, get_loop_indices, get_matrix_world, get_data,
get_objects, get_rotation_euler, get_tail, get_uv_layers, matmul,
set_matrix, set_matrix_parent_inverse, set_matrix_world,
get_matrix_parent_inverse, get_pose_bones, subtract)
from .common import (
MINECRAFT_SCALE_FACTOR, CubePolygons, CubePolygon, MeshType)
Expand Down Expand Up @@ -244,7 +245,6 @@ def _load_format_version(self, data: Dict) -> Tuple[str, str]:
:param data: JSON dict with model file.
'''
# pylint: disable=no-self-use
if 'format_version' in data:
parser_version = pick_version_parser(
('1.16.0', '1.12.0', '1.8.0'), data['format_version'])
Expand Down Expand Up @@ -701,7 +701,6 @@ def _create_default_uv(
:param uv: Optional - the UV property of the cube (if the cube uses the
standard Minecraft UV mapping format).
'''
# pylint: disable=no-self-use
width, height, depth = (int(i) for i in size)

def _face(size: Vector2d, uv: Vector2d):
Expand Down Expand Up @@ -1488,7 +1487,7 @@ def build_with_empties(
mesh.use_auto_smooth = True
mesh.normals_split_custom_set(
blender_normals) # type: ignore

if get_uv_layers(mesh).active is None:
get_uv_layers(mesh).new()
uv_layer = get_data(get_uv_layers(mesh).active)
Expand Down
1 change: 0 additions & 1 deletion mcblend/operator_func/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import numpy as np
import mathutils
from mathutils import Vector
import bpy
from bpy.types import MeshUVLoopLayer, MeshPolygon


Expand Down
Loading

0 comments on commit 1cdd56f

Please sign in to comment.