From 4a9a92158308fe7daf391e8e708177f17f846792 Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Tue, 7 Sep 2021 00:02:59 -0700 Subject: [PATCH 01/19] WIP import functionality (PSK working, PSA in the works) --- io_export_psk_psa/__init__.py | 42 ++++++++++++++--- io_export_psk_psa/data.py | 6 +++ io_export_psk_psa/psa/data.py | 2 +- io_export_psk_psa/psa/importer.py | 15 ++++++ io_export_psk_psa/psa/operator.py | 77 +++++++++++++++++++++++++++++-- io_export_psk_psa/psa/reader.py | 53 +++++++++++++++++++++ io_export_psk_psa/psk/builder.py | 6 +-- io_export_psk_psa/psk/data.py | 4 +- io_export_psk_psa/psk/importer.py | 71 ++++++++++++++++++++++++++++ io_export_psk_psa/psk/operator.py | 23 ++++++++- io_export_psk_psa/psk/reader.py | 46 ++++++++++++++++++ 11 files changed, 327 insertions(+), 18 deletions(-) create mode 100644 io_export_psk_psa/psa/importer.py create mode 100644 io_export_psk_psa/psa/reader.py create mode 100644 io_export_psk_psa/psk/importer.py create mode 100644 io_export_psk_psa/psk/reader.py diff --git a/io_export_psk_psa/__init__.py b/io_export_psk_psa/__init__.py index 53c00ac..044333d 100644 --- a/io_export_psk_psa/__init__.py +++ b/io_export_psk_psa/__init__.py @@ -16,55 +16,83 @@ if 'bpy' in locals(): importlib.reload(psk_data) importlib.reload(psk_builder) importlib.reload(psk_exporter) + importlib.reload(psk_importer) + importlib.reload(psk_reader) importlib.reload(psk_operator) importlib.reload(psa_data) importlib.reload(psa_builder) importlib.reload(psa_exporter) importlib.reload(psa_operator) + importlib.reload(psa_reader) + importlib.reload(psa_importer) else: # if i remove this line, it can be enabled just fine from .psk import data as psk_data from .psk import builder as psk_builder from .psk import exporter as psk_exporter + from .psk import reader as psk_reader + from .psk import importer as psk_importer from .psk import operator as psk_operator from .psa import data as psa_data from .psa import builder as psa_builder from .psa import exporter as psa_exporter from .psa import operator as psa_operator + from .psa import reader as psa_reader + from .psa import importer as psa_importer import bpy from bpy.props import IntProperty, CollectionProperty classes = [ psk_operator.PskExportOperator, + psk_operator.PskImportOperator, psa_operator.PsaExportOperator, + psa_operator.PsaImportOperator, psa_operator.PSA_UL_ActionList, - psa_operator.ActionListItem + psa_operator.PSA_UL_ImportActionList, + psa_operator.ActionListItem, + psa_operator.ImportActionListItem ] -def psk_menu_func(self, context): +def psk_export_menu_func(self, context): self.layout.operator(psk_operator.PskExportOperator.bl_idname, text ='Unreal PSK (.psk)') -def psa_menu_func(self, context): +def psk_import_menu_func(self, context): + self.layout.operator(psk_operator.PskImportOperator.bl_idname, text ='Unreal PSK (.psk)') + + +def psa_export_menu_func(self, context): self.layout.operator(psa_operator.PsaExportOperator.bl_idname, text='Unreal PSA (.psa)') +def psa_import_menu_func(self, context): + self.layout.operator(psa_operator.PsaImportOperator.bl_idname, text ='Unreal PSA (.psa)') + + def register(): for cls in classes: bpy.utils.register_class(cls) - bpy.types.TOPBAR_MT_file_export.append(psk_menu_func) - bpy.types.TOPBAR_MT_file_export.append(psa_menu_func) + bpy.types.TOPBAR_MT_file_export.append(psk_export_menu_func) + bpy.types.TOPBAR_MT_file_import.append(psk_import_menu_func) + bpy.types.TOPBAR_MT_file_export.append(psa_export_menu_func) + bpy.types.TOPBAR_MT_file_import.append(psa_import_menu_func) bpy.types.Scene.psa_action_list = CollectionProperty(type=psa_operator.ActionListItem) + bpy.types.Scene.psa_import_action_list = CollectionProperty(type=psa_operator.ImportActionListItem) bpy.types.Scene.psa_action_list_index = IntProperty(name='index for list??', default=0) + bpy.types.Scene.psa_import_action_list_index = IntProperty(name='index for list??', default=0) def unregister(): del bpy.types.Scene.psa_action_list_index + del bpy.types.Scene.psa_import_action_list_index del bpy.types.Scene.psa_action_list - bpy.types.TOPBAR_MT_file_export.remove(psa_menu_func) - bpy.types.TOPBAR_MT_file_export.remove(psk_menu_func) + del bpy.types.Scene.psa_import_action_list + bpy.types.TOPBAR_MT_file_export.remove(psk_export_menu_func) + bpy.types.TOPBAR_MT_file_import.remove(psk_import_menu_func) + bpy.types.TOPBAR_MT_file_export.remove(psa_export_menu_func) + bpy.types.TOPBAR_MT_file_import.remove(psa_import_menu_func) for cls in reversed(classes): bpy.utils.unregister_class(cls) diff --git a/io_export_psk_psa/data.py b/io_export_psk_psa/data.py index 91d9386..e48a6b2 100644 --- a/io_export_psk_psa/data.py +++ b/io_export_psk_psa/data.py @@ -17,6 +17,12 @@ class Quaternion(Structure): ('w', c_float), ] + def __iter__(self): + yield self.x + yield self.y + yield self.z + yield self.w + class Section(Structure): _fields_ = [ diff --git a/io_export_psk_psa/psa/data.py b/io_export_psk_psa/psa/data.py index adf744d..85e8344 100644 --- a/io_export_psk_psa/psa/data.py +++ b/io_export_psk_psa/psa/data.py @@ -22,7 +22,7 @@ class Psa(object): ('bone_count', c_int32), ('root_include', c_int32), ('compression_style', c_int32), - ('key_quotum', c_int32), # what the fuck is a quotum + ('key_quotum', c_int32), ('key_reduction', c_float), ('track_time', c_float), ('fps', c_float), diff --git a/io_export_psk_psa/psa/importer.py b/io_export_psk_psa/psa/importer.py new file mode 100644 index 0000000..9e79ffa --- /dev/null +++ b/io_export_psk_psa/psa/importer.py @@ -0,0 +1,15 @@ +import bpy +import bmesh +import mathutils +from .data import Psa + + +class PsaImporter(object): + def __init__(self): + pass + + def import_psa(self, psa: Psa, context): + print('importing yay') + print(psa.sequences) + for sequence in psa.sequences: + print(sequence.name, sequence.frame_start_index, sequence.frame_count) diff --git a/io_export_psk_psa/psa/operator.py b/io_export_psk_psa/psa/operator.py index 817b778..085c9f8 100644 --- a/io_export_psk_psa/psa/operator.py +++ b/io_export_psk_psa/psa/operator.py @@ -1,12 +1,23 @@ from bpy.types import Operator, Action, UIList, PropertyGroup -from bpy_extras.io_utils import ExportHelper +from bpy_extras.io_utils import ExportHelper, ImportHelper from bpy.props import StringProperty, BoolProperty, CollectionProperty, PointerProperty from .builder import PsaBuilder, PsaBuilderOptions from .exporter import PsaExporter +from .reader import PsaReader +from .importer import PsaImporter import bpy import re +class ImportActionListItem(PropertyGroup): + action_name: StringProperty() + is_selected: BoolProperty(default=True) + + @property + def name(self): + return self.action_name + + class ActionListItem(PropertyGroup): action: PointerProperty(type=Action) is_selected: BoolProperty(default=False) @@ -16,6 +27,22 @@ class ActionListItem(PropertyGroup): return self.action.name +class PSA_UL_ImportActionList(UIList): + def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): + layout.alignment = 'LEFT' + layout.prop(item, 'is_selected', icon_only=True) + layout.label(text=item.action_name) + + # def filter_items(self, context, data, property): + # # TODO: returns two lists, apparently + # actions = getattr(data, property) + # flt_flags = [] + # flt_neworder = [] + # if self.filter_name: + # flt_flags = bpy.types.UI_UL_list.filter_items_by_name(self.filter_name, self.bitflag_filter_item, actions, 'name', reverse=self.use_filter_invert) + # return flt_flags, flt_neworder + + class PSA_UL_ActionList(UIList): def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): layout.alignment = 'LEFT' @@ -37,8 +64,8 @@ class PsaExportOperator(Operator, ExportHelper): bl_label = 'Export' __doc__ = 'PSA Exporter (.psa)' filename_ext = '.psa' - filter_glob : StringProperty(default='*.psa', options={'HIDDEN'}) - filepath : StringProperty( + filter_glob: StringProperty(default='*.psa', options={'HIDDEN'}) + filepath: StringProperty( name='File Path', description='File path used for exporting the PSA file', maxlen=1024, @@ -103,3 +130,47 @@ class PsaExportOperator(Operator, ExportHelper): exporter = PsaExporter(psk) exporter.export(self.filepath) return {'FINISHED'} + + +class PsaImportOperator(Operator, ImportHelper): + # TODO: list out the actions to be imported + bl_idname = 'import.psa' + bl_label = 'Import' + __doc__ = 'PSA Importer (.psa)' + filename_ext = '.psa' + filter_glob: StringProperty(default='*.psa', options={'HIDDEN'}) + filepath: StringProperty( + name='File Path', + description='File path used for importing the PSA file', + maxlen=1024, + default='') + + def invoke(self, context, event): + action_names = [] + try: + action_names = PsaReader().scan_sequence_names(self.filepath) + except IOError: + pass + + context.scene.psa_import_action_list.clear() + for action_name in action_names: + item = context.scene.psa_action_list.add() + item.action_name = action_name + item.is_selected = True + + context.window_manager.fileselect_add(self) + return {'RUNNING_MODAL'} + + def draw(self, context): + layout = self.layout + scene = context.scene + box = layout.box() + box.label(text='Actions', icon='ACTION') + row = box.row() + row.template_list('PSA_UL_ImportActionList', 'asd', scene, 'psa_import_action_list', scene, 'psa_import_action_list_index', rows=len(context.scene.psa_import_action_list)) + + def execute(self, context): + reader = PsaReader() + psa = reader.read(self.filepath) + PsaImporter().import_psa(psa, context) + return {'FINISHED'} diff --git a/io_export_psk_psa/psa/reader.py b/io_export_psk_psa/psa/reader.py new file mode 100644 index 0000000..8ad2611 --- /dev/null +++ b/io_export_psk_psa/psa/reader.py @@ -0,0 +1,53 @@ +from .data import * +from typing import AnyStr +import ctypes + + +class PsaReader(object): + + def __init__(self): + pass + + @staticmethod + def read_types(fp, data_class: ctypes.Structure, section: Section, data): + buffer_length = section.data_size * section.data_count + buffer = fp.read(buffer_length) + offset = 0 + for _ in range(section.data_count): + data.append(data_class.from_buffer_copy(buffer, offset)) + offset += section.data_size + + def scan_sequence_names(self, path) -> List[AnyStr]: + sequences = [] + with open(path, 'rb') as fp: + if fp.read(8) != b'ANIMINFO': + raise IOError('Unexpected file format') + fp.seek(0, 0) + while fp.read(1): + fp.seek(-1, 1) + section = Section.from_buffer_copy(fp.read(ctypes.sizeof(Section))) + if section.name == b'ANIMINFO': + PsaReader.read_types(fp, Psa.Sequence, section, sequences) + return [sequence.name for sequence in sequences] + else: + fp.seek(section.data_size * section.data_count, 1) + return [] + + def read(self, path) -> Psa: + psa = Psa() + with open(path, 'rb') as fp: + while fp.read(1): + fp.seek(-1, 1) + section = Section.from_buffer_copy(fp.read(ctypes.sizeof(Section))) + if section.name == b'ANIMHEAD': + pass + elif section.name == b'BONENAMES': + PsaReader.read_types(fp, Psa.Bone, section, psa.bones) + elif section.name == b'ANIMINFO': + PsaReader.read_types(fp, Psa.Sequence, section, psa.sequences) + elif section.name == b'ANIMKEYS': + PsaReader.read_types(fp, Psa.Key, section, psa.keys) + else: + raise RuntimeError(f'Unrecognized section "{section.name}"') + return psa +1 \ No newline at end of file diff --git a/io_export_psk_psa/psk/builder.py b/io_export_psk_psa/psk/builder.py index 88790a7..5a783cc 100644 --- a/io_export_psk_psa/psk/builder.py +++ b/io_export_psk_psa/psk/builder.py @@ -159,9 +159,9 @@ class PskBuilder(object): for f in object.data.loop_triangles: face = Psk.Face() face.material_index = material_indices[f.material_index] - face.wedge_index_1 = f.loops[2] + wedge_offset - face.wedge_index_2 = f.loops[1] + wedge_offset - face.wedge_index_3 = f.loops[0] + wedge_offset + face.wedge_indices[0] = f.loops[2] + wedge_offset + face.wedge_indices[1] = f.loops[1] + wedge_offset + face.wedge_indices[2] = f.loops[0] + wedge_offset face.smoothing_groups = poly_groups[f.polygon_index] psk.faces.append(face) # update the material index of the wedges diff --git a/io_export_psk_psa/psk/data.py b/io_export_psk_psa/psk/data.py index cf8d545..80fd441 100644 --- a/io_export_psk_psa/psk/data.py +++ b/io_export_psk_psa/psk/data.py @@ -25,9 +25,7 @@ class Psk(object): class Face(Structure): _fields_ = [ - ('wedge_index_1', c_int16), - ('wedge_index_2', c_int16), - ('wedge_index_3', c_int16), + ('wedge_indices', c_int16 * 3), ('material_index', c_int8), ('aux_material_index', c_int8), ('smoothing_groups', c_int32) diff --git a/io_export_psk_psa/psk/importer.py b/io_export_psk_psa/psk/importer.py new file mode 100644 index 0000000..df2da4b --- /dev/null +++ b/io_export_psk_psa/psk/importer.py @@ -0,0 +1,71 @@ +import bpy +import bmesh +import mathutils +from .data import Psk + + +class PskImporter(object): + def __init__(self): + pass + + def import_psk(self, psk: Psk, context): + # ARMATURE + armature_data = bpy.data.armatures.new('armature') + armature_object = bpy.data.objects.new('new_ao', armature_data) + context.scene.collection.objects.link(armature_object) + + try: + bpy.ops.object.mode_set(mode='OBJECT') + except: + pass + + armature_object.select_set(state=True) + bpy.context.view_layer.objects.active = armature_object + + bpy.ops.object.mode_set(mode='EDIT') + + for bone in psk.bones: + edit_bone = armature_data.edit_bones.new(bone.name.decode('utf-8')) + edit_bone.parent = armature_data.edit_bones[bone.parent_index] + edit_bone.head = (bone.location.x, bone.location.y, bone.location.z) + rotation = mathutils.Quaternion(*bone.rotation) + edit_bone.tail = edit_bone.head + (mathutils.Vector(0, 0, 1) @ rotation) + + # MESH + mesh_data = bpy.data.meshes.new('mesh') + mesh_object = bpy.data.objects.new('new_mo', mesh_data) + + # MATERIALS + for material in psk.materials: + bpy_material = bpy.data.materials.new(material.name.decode('utf-8')) + mesh_data.materials.append(bpy_material) + + bm = bmesh.new() + + # VERTICES + for point in psk.points: + bm.verts.new((point.x, point.y, point.z)) + + bm.verts.ensure_lookup_table() + + for face in psk.faces: + point_indices = [bm.verts[psk.wedges[i].point_index] for i in reversed(face.wedge_indices)] + bm_face = bm.faces.new(point_indices) + bm_face.material_index = face.material_index + + bm.to_mesh(mesh_data) + + # TEXTURE COORDINATES + data_index = 0 + uv_layer = mesh_data.uv_layers.new() + for face_index, face in enumerate(psk.faces): + face_wedges = [psk.wedges[i] for i in reversed(face.wedge_indices)] + for wedge in face_wedges: + uv_layer.data[data_index].uv = wedge.u, 1.0 - wedge.v + data_index += 1 + + bm.free() + + # TODO: weights (vertex grorups etc.) + + context.scene.collection.objects.link(mesh_object) diff --git a/io_export_psk_psa/psk/operator.py b/io_export_psk_psa/psk/operator.py index 0291385..1826550 100644 --- a/io_export_psk_psa/psk/operator.py +++ b/io_export_psk_psa/psk/operator.py @@ -1,8 +1,29 @@ from bpy.types import Operator -from bpy_extras.io_utils import ExportHelper +from bpy_extras.io_utils import ExportHelper, ImportHelper from bpy.props import StringProperty, BoolProperty, FloatProperty from .builder import PskBuilder from .exporter import PskExporter +from .reader import PskReader +from .importer import PskImporter + + +class PskImportOperator(Operator, ImportHelper): + bl_idname = 'import.psk' + bl_label = 'Export' + __doc__ = 'PSK Importer (.psk)' + filename_ext = '.psk' + filter_glob: StringProperty(default='*.psk', options={'HIDDEN'}) + filepath: StringProperty( + name='File Path', + description='File path used for exporting the PSK file', + maxlen=1024, + default='') + + def execute(self, context): + reader = PskReader() + psk = reader.read(self.filepath) + PskImporter().import_psk(psk, context) + return {'FINISHED'} class PskExportOperator(Operator, ExportHelper): diff --git a/io_export_psk_psa/psk/reader.py b/io_export_psk_psa/psk/reader.py new file mode 100644 index 0000000..8f94c36 --- /dev/null +++ b/io_export_psk_psa/psk/reader.py @@ -0,0 +1,46 @@ +from .data import * +import ctypes + + +class PskReader(object): + + def __init__(self): + pass + + @staticmethod + def read_types(fp, data_class: ctypes.Structure, section: Section, data): + buffer_length = section.data_size * section.data_count + buffer = fp.read(buffer_length) + offset = 0 + for _ in range(section.data_count): + data.append(data_class.from_buffer_copy(buffer, offset)) + offset += section.data_size + + def read(self, path) -> Psk: + psk = Psk() + with open(path, 'rb') as fp: + while fp.read(1): + fp.seek(-1, 1) + section = Section.from_buffer_copy(fp.read(ctypes.sizeof(Section))) + if section.name == b'ACTRHEAD': + pass + elif section.name == b'PNTS0000': + PskReader.read_types(fp, Vector3, section, psk.points) + elif section.name == b'VTXW0000': + if section.data_size == ctypes.sizeof(Psk.Wedge16): + PskReader.read_types(fp, Psk.Wedge16, section, psk.wedges) + elif section.data_size == ctypes.sizeof(Psk.Wedge32): + PskReader.read_types(fp, Psk.Wedge32, section, psk.wedges) + else: + raise RuntimeError('Unrecognized wedge format') + elif section.name == b'FACE0000': + PskReader.read_types(fp, Psk.Face, section, psk.faces) + elif section.name == b'MATT0000': + PskReader.read_types(fp, Psk.Material, section, psk.materials) + elif section.name == b'REFSKELT': + PskReader.read_types(fp, Psk.Bone, section, psk.bones) + elif section.name == b'RAWWEIGHTS': + PskReader.read_types(fp, Psk.Weight, section, psk.weights) + else: + raise RuntimeError(f'Unrecognized section "{section.name}"') + return psk From 9fa0780032cf4be126874de0b01ab575df37bb8d Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Fri, 14 Jan 2022 12:26:35 -0800 Subject: [PATCH 02/19] * PSK importer now working * Fleshing out PSA importer (not done yet but getting there) --- io_export_psk_psa/__init__.py | 49 ++++--- io_export_psk_psa/data.py | 7 +- io_export_psk_psa/psa/data.py | 4 +- io_export_psk_psa/psa/exporter.py | 95 +++++++++++++ io_export_psk_psa/psa/importer.py | 212 +++++++++++++++++++++++++++++- io_export_psk_psa/psa/operator.py | 176 ------------------------- io_export_psk_psa/psa/reader.py | 10 +- io_export_psk_psa/psk/data.py | 4 +- io_export_psk_psa/psk/exporter.py | 62 +++++++-- io_export_psk_psa/psk/importer.py | 124 +++++++++++++++-- io_export_psk_psa/psk/operator.py | 57 -------- 11 files changed, 504 insertions(+), 296 deletions(-) delete mode 100644 io_export_psk_psa/psa/operator.py delete mode 100644 io_export_psk_psa/psk/operator.py diff --git a/io_export_psk_psa/__init__.py b/io_export_psk_psa/__init__.py index 044333d..0921161 100644 --- a/io_export_psk_psa/__init__.py +++ b/io_export_psk_psa/__init__.py @@ -18,11 +18,9 @@ if 'bpy' in locals(): importlib.reload(psk_exporter) importlib.reload(psk_importer) importlib.reload(psk_reader) - importlib.reload(psk_operator) importlib.reload(psa_data) importlib.reload(psa_builder) importlib.reload(psa_exporter) - importlib.reload(psa_operator) importlib.reload(psa_reader) importlib.reload(psa_importer) else: @@ -32,43 +30,48 @@ else: from .psk import exporter as psk_exporter from .psk import reader as psk_reader from .psk import importer as psk_importer - from .psk import operator as psk_operator from .psa import data as psa_data from .psa import builder as psa_builder from .psa import exporter as psa_exporter - from .psa import operator as psa_operator from .psa import reader as psa_reader from .psa import importer as psa_importer import bpy -from bpy.props import IntProperty, CollectionProperty +from bpy.props import PointerProperty + classes = [ - psk_operator.PskExportOperator, - psk_operator.PskImportOperator, - psa_operator.PsaExportOperator, - psa_operator.PsaImportOperator, - psa_operator.PSA_UL_ActionList, - psa_operator.PSA_UL_ImportActionList, - psa_operator.ActionListItem, - psa_operator.ImportActionListItem + psk_exporter.PskExportOperator, + psk_importer.PskImportOperator, + psa_exporter.PsaExportOperator, + psa_importer.PsaImportOperator, + psa_importer.PsaImportFileSelectOperator, + psa_importer.PSA_UL_ActionList, + psa_importer.PSA_UL_ImportActionList, + psa_exporter.PsaExportActionListItem, + psa_importer.PsaImportActionListItem, + psa_importer.PsaImportSelectAll, + psa_importer.PsaImportDeselectAll, + psa_importer.PSA_PT_ImportPanel, + psa_importer.PsaImportPropertyGroup, + psa_exporter.PsaExportPropertyGroup, ] def psk_export_menu_func(self, context): - self.layout.operator(psk_operator.PskExportOperator.bl_idname, text ='Unreal PSK (.psk)') + self.layout.operator(psk_exporter.PskExportOperator.bl_idname, text='Unreal PSK (.psk)') def psk_import_menu_func(self, context): - self.layout.operator(psk_operator.PskImportOperator.bl_idname, text ='Unreal PSK (.psk)') + self.layout.operator(psk_importer.PskImportOperator.bl_idname, text='Unreal PSK (.psk)') def psa_export_menu_func(self, context): - self.layout.operator(psa_operator.PsaExportOperator.bl_idname, text='Unreal PSA (.psa)') + self.layout.operator(psa_exporter.PsaExportOperator.bl_idname, text='Unreal PSA (.psa)') def psa_import_menu_func(self, context): - self.layout.operator(psa_operator.PsaImportOperator.bl_idname, text ='Unreal PSA (.psa)') + self.layout.operator(psa_importer.PsaImportOperator.bl_idname, text='Unreal PSA (.psa)') def register(): @@ -78,17 +81,13 @@ def register(): bpy.types.TOPBAR_MT_file_import.append(psk_import_menu_func) bpy.types.TOPBAR_MT_file_export.append(psa_export_menu_func) bpy.types.TOPBAR_MT_file_import.append(psa_import_menu_func) - bpy.types.Scene.psa_action_list = CollectionProperty(type=psa_operator.ActionListItem) - bpy.types.Scene.psa_import_action_list = CollectionProperty(type=psa_operator.ImportActionListItem) - bpy.types.Scene.psa_action_list_index = IntProperty(name='index for list??', default=0) - bpy.types.Scene.psa_import_action_list_index = IntProperty(name='index for list??', default=0) + bpy.types.Scene.psa_import = PointerProperty(type=psa_importer.PsaImportPropertyGroup) + bpy.types.Scene.psa_export = PointerProperty(type=psa_exporter.PsaExportPropertyGroup) def unregister(): - del bpy.types.Scene.psa_action_list_index - del bpy.types.Scene.psa_import_action_list_index - del bpy.types.Scene.psa_action_list - del bpy.types.Scene.psa_import_action_list + del bpy.types.Scene.psa_export + del bpy.types.Scene.psa_import bpy.types.TOPBAR_MT_file_export.remove(psk_export_menu_func) bpy.types.TOPBAR_MT_file_import.remove(psk_import_menu_func) bpy.types.TOPBAR_MT_file_export.remove(psa_export_menu_func) diff --git a/io_export_psk_psa/data.py b/io_export_psk_psa/data.py index e48a6b2..a9a9a8f 100644 --- a/io_export_psk_psa/data.py +++ b/io_export_psk_psa/data.py @@ -8,6 +8,11 @@ class Vector3(Structure): ('z', c_float), ] + def __iter__(self): + yield self.x + yield self.y + yield self.z + class Quaternion(Structure): _fields_ = [ @@ -18,10 +23,10 @@ class Quaternion(Structure): ] def __iter__(self): + yield self.w yield self.x yield self.y yield self.z - yield self.w class Section(Structure): diff --git a/io_export_psk_psa/psa/data.py b/io_export_psk_psa/psa/data.py index 85e8344..b43503c 100644 --- a/io_export_psk_psa/psa/data.py +++ b/io_export_psk_psa/psa/data.py @@ -1,4 +1,4 @@ -from typing import List +from typing import List, Dict from ..data import * @@ -40,5 +40,5 @@ class Psa(object): def __init__(self): self.bones: List[Psa.Bone] = [] - self.sequences: List[Psa.Sequence] = [] + self.sequences: Dict[Psa.Sequence] = {} self.keys: List[Psa.Key] = [] diff --git a/io_export_psk_psa/psa/exporter.py b/io_export_psk_psa/psa/exporter.py index d48cdbf..eb81509 100644 --- a/io_export_psk_psa/psa/exporter.py +++ b/io_export_psk_psa/psa/exporter.py @@ -1,5 +1,11 @@ +import bpy +from bpy.types import Operator, PropertyGroup, Action +from bpy.props import CollectionProperty, IntProperty, PointerProperty, StringProperty, BoolProperty +from bpy_extras.io_utils import ExportHelper from typing import Type +from .builder import PsaBuilder, PsaBuilderOptions from .data import * +import re class PsaExporter(object): @@ -25,3 +31,92 @@ class PsaExporter(object): self.write_section(fp, b'BONENAMES', Psa.Bone, self.psa.bones) self.write_section(fp, b'ANIMINFO', Psa.Sequence, self.psa.sequences) self.write_section(fp, b'ANIMKEYS', Psa.Key, self.psa.keys) + + +class PsaExportActionListItem(PropertyGroup): + action: PointerProperty(type=Action) + is_selected: BoolProperty(default=False) + + @property + def name(self): + return self.action.name + + +class PsaExportPropertyGroup(bpy.types.PropertyGroup): + action_list: CollectionProperty(type=PsaExportActionListItem) + import_action_list: CollectionProperty(type=PsaExportActionListItem) + action_list_index: IntProperty(name='index for list??', default=0) + import_action_list_index: IntProperty(name='index for list??', default=0) + + +class PsaExportOperator(Operator, ExportHelper): + bl_idname = 'export.psa' + bl_label = 'Export' + __doc__ = 'PSA Exporter (.psa)' + filename_ext = '.psa' + filter_glob: StringProperty(default='*.psa', options={'HIDDEN'}) + filepath: StringProperty( + name='File Path', + description='File path used for exporting the PSA file', + maxlen=1024, + default='') + + def __init__(self): + self.armature = None + + def draw(self, context): + layout = self.layout + scene = context.scene + box = layout.box() + box.label(text='Actions', icon='ACTION') + row = box.row() + row.template_list('PSA_UL_ActionList', 'asd', scene, 'psa_export.action_list', scene, 'psa_export.action_list_index', rows=len(context.scene.psa_export.action_list)) + + def is_action_for_armature(self, action): + if len(action.fcurves) == 0: + return False + bone_names = set([x.name for x in self.armature.data.bones]) + for fcurve in action.fcurves: + match = re.match(r'pose\.bones\["(.+)"\].\w+', fcurve.data_path) + if not match: + continue + bone_name = match.group(1) + if bone_name in bone_names: + return True + return False + + def invoke(self, context, event): + if context.view_layer.objects.active.type != 'ARMATURE': + self.report({'ERROR_INVALID_CONTEXT'}, 'The selected object must be an armature.') + return {'CANCELLED'} + + self.armature = context.view_layer.objects.active + + context.scene.psa_export.action_list.clear() + for action in bpy.data.actions: + item = context.scene.psa_export.action_list.add() + item.action = action + if self.is_action_for_armature(action): + item.is_selected = True + + if len(context.scene.psa_export.action_list) == 0: + self.report({'ERROR_INVALID_CONTEXT'}, 'There are no actions to export.') + return {'CANCELLED'} + + context.window_manager.fileselect_add(self) + return {'RUNNING_MODAL'} + + def execute(self, context): + actions = [x.action for x in context.scene.psa_export.action_list if x.is_selected] + + if len(actions) == 0: + self.report({'ERROR_INVALID_CONTEXT'}, 'No actions were selected for export.') + return {'CANCELLED'} + + options = PsaBuilderOptions() + options.actions = actions + builder = PsaBuilder() + psa = builder.build(context, options) + exporter = PsaExporter(psa) + exporter.export(self.filepath) + return {'FINISHED'} diff --git a/io_export_psk_psa/psa/importer.py b/io_export_psk_psa/psa/importer.py index 9e79ffa..a3198f6 100644 --- a/io_export_psk_psa/psa/importer.py +++ b/io_export_psk_psa/psa/importer.py @@ -1,15 +1,215 @@ import bpy -import bmesh import mathutils from .data import Psa +from typing import List, AnyStr +import bpy +from bpy.types import Operator, Action, UIList, PropertyGroup, Panel, Armature +from bpy_extras.io_utils import ExportHelper, ImportHelper +from bpy.props import StringProperty, BoolProperty, CollectionProperty, PointerProperty, IntProperty +from .reader import PsaReader class PsaImporter(object): def __init__(self): pass - def import_psa(self, psa: Psa, context): - print('importing yay') - print(psa.sequences) - for sequence in psa.sequences: - print(sequence.name, sequence.frame_start_index, sequence.frame_count) + def import_psa(self, psa: Psa, sequence_names: List[AnyStr], context): + properties = context.scene.psa_import + sequences = map(lambda x: psa.sequences[x], sequence_names) + + armature_object = properties.armature_object + armature_data = armature_object.data + + # create an index mapping from bones in the PSA to bones in the target armature. + bone_indices = {} + data_bone_names = [x.name for x in armature_data.bones] + for index, psa_bone in enumerate(psa.bones): + psa_bone_name = psa_bone.name.decode() + try: + bone_indices[index] = data_bone_names.index(psa_bone_name) + except ValueError: + pass + del data_bone_names + + for sequence in sequences: + action = bpy.data.actions.new(name=sequence.name.decode()) + for psa_bone_index, armature_bone_index in bone_indices.items(): + psa_bone = psa.bones[psa_bone_index] + pose_bone = armature_object.pose.bones[armature_bone_index] + + # rotation + rotation_data_path = pose_bone.path_from_id('rotation_quaternion') + fcurve_quat_w = action.fcurves.new(rotation_data_path, index=0) + fcurve_quat_x = action.fcurves.new(rotation_data_path, index=0) + fcurve_quat_y = action.fcurves.new(rotation_data_path, index=0) + fcurve_quat_z = action.fcurves.new(rotation_data_path, index=0) + + # location + location_data_path = pose_bone.path_from_id('location') + fcurve_location_x = action.fcurves.new(location_data_path, index=0) + fcurve_location_y = action.fcurves.new(location_data_path, index=1) + fcurve_location_z = action.fcurves.new(location_data_path, index=2) + + # add keyframes + fcurve_quat_w.keyframe_points.add(sequence.frame_count) + fcurve_quat_x.keyframe_points.add(sequence.frame_count) + fcurve_quat_y.keyframe_points.add(sequence.frame_count) + fcurve_quat_z.keyframe_points.add(sequence.frame_count) + fcurve_location_x.keyframe_points.add(sequence.frame_count) + fcurve_location_y.keyframe_points.add(sequence.frame_count) + fcurve_location_z.keyframe_points.add(sequence.frame_count) + + raw_key_index = 0 # ? + for frame_index in range(sequence.frame_count): + for psa_bone_index in range(len(psa.bones)): + if psa_bone_index not in bone_indices: + # bone does not exist in the armature, skip it + raw_key_index += 1 + continue + psa_bone = psa.bones[psa_bone_index] + + # ... + + raw_key_index += 1 + + +class PsaImportActionListItem(PropertyGroup): + action_name: StringProperty() + is_selected: BoolProperty(default=True) + + @property + def name(self): + return self.action_name + + +class PsaImportPropertyGroup(bpy.types.PropertyGroup): + cool_filepath: StringProperty(default='') + armature_object: PointerProperty(type=bpy.types.Object) # TODO: figure out how to filter this to only objects of a specific type + action_list: CollectionProperty(type=PsaImportActionListItem) + import_action_list: CollectionProperty(type=PsaImportActionListItem) + action_list_index: IntProperty(name='index for list??', default=0) + import_action_list_index: IntProperty(name='index for list??', default=0) + + +class PSA_UL_ImportActionList(UIList): + def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): + layout.alignment = 'LEFT' + layout.prop(item, 'is_selected', icon_only=True) + layout.label(text=item.action_name) + + def filter_items(self, context, data, property): + # TODO: returns two lists, apparently + actions = getattr(data, property) + flt_flags = [] + flt_neworder = [] + if self.filter_name: + flt_flags = bpy.types.UI_UL_list.filter_items_by_name( + self.filter_name, + self.bitflag_filter_item, + actions, + 'action_name', + reverse=self.use_filter_invert + ) + return flt_flags, flt_neworder + + +class PSA_UL_ActionList(UIList): + def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): + layout.alignment = 'LEFT' + layout.prop(item, 'is_selected', icon_only=True) + layout.label(text=item.action.name) + + def filter_items(self, context, data, property): + # TODO: returns two lists, apparently + actions = getattr(data, property) + flt_flags = [] + flt_neworder = [] + if self.filter_name: + flt_flags = bpy.types.UI_UL_list.filter_items_by_name(self.filter_name, self.bitflag_filter_item, actions, 'name', reverse=self.use_filter_invert) + return flt_flags, flt_neworder + + +class PsaImportSelectAll(bpy.types.Operator): + bl_idname = 'psa_import.actions_select_all' + bl_label = 'Select All' + + def execute(self, context): + for action in context.scene.psa_import.action_list: + action.is_selected = True + return {'FINISHED'} + + +class PsaImportDeselectAll(bpy.types.Operator): + bl_idname = 'psa_import.actions_deselect_all' + bl_label = 'Deselect All' + + def execute(self, context): + for action in context.scene.psa_import.action_list: + action.is_selected = False + return {'FINISHED'} + + +class PSA_PT_ImportPanel(Panel): + bl_space_type = 'VIEW_3D' + bl_region_type = 'UI' + bl_label = 'PSA Import' + bl_context = 'objectmode' + bl_category = 'PSA Import' + + def draw(self, context): + layout = self.layout + scene = context.scene + row = layout.row() + row.operator('psa_import.file_select', icon='FILE_FOLDER', text='') + row.label(text=scene.psa_import.cool_filepath) + box = layout.box() + box.label(text='Actions', icon='ACTION') + row = box.row() + row.template_list('PSA_UL_ImportActionList', 'asd', scene.psa_import, 'action_list', scene.psa_import, 'action_list_index', rows=10) + row = box.row() + row.operator('psa_import.actions_select_all', text='Select All') + row.operator('psa_import.actions_deselect_all', text='Deselect All') + layout.prop(scene.psa_import, 'armature_object', icon_only=True) + layout.operator('psa_import.import', text='Import') + + +class PsaImportOperator(Operator): + bl_idname = 'psa_import.import' + bl_label = 'Import' + + def execute(self, context): + psa = PsaReader().read(context.scene.psa_import.cool_filepath) + sequence_names = [x.action_name for x in context.scene.psa_import.action_list if x.is_selected] + PsaImporter().import_psa(psa, sequence_names, context) + return {'FINISHED'} + + +class PsaImportFileSelectOperator(Operator, ImportHelper): + bl_idname = 'psa_import.file_select' + bl_label = 'File Select' + filename_ext = '.psa' + filter_glob: StringProperty(default='*.psa', options={'HIDDEN'}) + filepath: StringProperty( + name='File Path', + description='File path used for importing the PSA file', + maxlen=1024, + default='') + + def invoke(self, context, event): + context.window_manager.fileselect_add(self) + return {'RUNNING_MODAL'} + + def execute(self, context): + context.scene.psa_import.cool_filepath = self.filepath + # Load the sequence names from the selected file + action_names = [] + try: + action_names = PsaReader().scan_sequence_names(self.filepath) + except IOError: + pass + context.scene.psa_import.action_list.clear() + for action_name in action_names: + item = context.scene.psa_import.action_list.add() + item.action_name = action_name.decode() + item.is_selected = True + return {'FINISHED'} diff --git a/io_export_psk_psa/psa/operator.py b/io_export_psk_psa/psa/operator.py deleted file mode 100644 index 085c9f8..0000000 --- a/io_export_psk_psa/psa/operator.py +++ /dev/null @@ -1,176 +0,0 @@ -from bpy.types import Operator, Action, UIList, PropertyGroup -from bpy_extras.io_utils import ExportHelper, ImportHelper -from bpy.props import StringProperty, BoolProperty, CollectionProperty, PointerProperty -from .builder import PsaBuilder, PsaBuilderOptions -from .exporter import PsaExporter -from .reader import PsaReader -from .importer import PsaImporter -import bpy -import re - - -class ImportActionListItem(PropertyGroup): - action_name: StringProperty() - is_selected: BoolProperty(default=True) - - @property - def name(self): - return self.action_name - - -class ActionListItem(PropertyGroup): - action: PointerProperty(type=Action) - is_selected: BoolProperty(default=False) - - @property - def name(self): - return self.action.name - - -class PSA_UL_ImportActionList(UIList): - def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): - layout.alignment = 'LEFT' - layout.prop(item, 'is_selected', icon_only=True) - layout.label(text=item.action_name) - - # def filter_items(self, context, data, property): - # # TODO: returns two lists, apparently - # actions = getattr(data, property) - # flt_flags = [] - # flt_neworder = [] - # if self.filter_name: - # flt_flags = bpy.types.UI_UL_list.filter_items_by_name(self.filter_name, self.bitflag_filter_item, actions, 'name', reverse=self.use_filter_invert) - # return flt_flags, flt_neworder - - -class PSA_UL_ActionList(UIList): - def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): - layout.alignment = 'LEFT' - layout.prop(item, 'is_selected', icon_only=True) - layout.label(text=item.action.name) - - def filter_items(self, context, data, property): - # TODO: returns two lists, apparently - actions = getattr(data, property) - flt_flags = [] - flt_neworder = [] - if self.filter_name: - flt_flags = bpy.types.UI_UL_list.filter_items_by_name(self.filter_name, self.bitflag_filter_item, actions, 'name', reverse=self.use_filter_invert) - return flt_flags, flt_neworder - - -class PsaExportOperator(Operator, ExportHelper): - bl_idname = 'export.psa' - bl_label = 'Export' - __doc__ = 'PSA Exporter (.psa)' - filename_ext = '.psa' - filter_glob: StringProperty(default='*.psa', options={'HIDDEN'}) - filepath: StringProperty( - name='File Path', - description='File path used for exporting the PSA file', - maxlen=1024, - default='') - - def __init__(self): - self.armature = None - - def draw(self, context): - layout = self.layout - scene = context.scene - box = layout.box() - box.label(text='Actions', icon='ACTION') - row = box.row() - row.template_list('PSA_UL_ActionList', 'asd', scene, 'psa_action_list', scene, 'psa_action_list_index', rows=len(context.scene.psa_action_list)) - - def is_action_for_armature(self, action): - if len(action.fcurves) == 0: - return False - bone_names = set([x.name for x in self.armature.data.bones]) - for fcurve in action.fcurves: - match = re.match(r'pose\.bones\["(.+)"\].\w+', fcurve.data_path) - if not match: - continue - bone_name = match.group(1) - if bone_name in bone_names: - return True - return False - - def invoke(self, context, event): - if context.view_layer.objects.active.type != 'ARMATURE': - self.report({'ERROR_INVALID_CONTEXT'}, 'The selected object must be an armature.') - return {'CANCELLED'} - - self.armature = context.view_layer.objects.active - - context.scene.psa_action_list.clear() - for action in bpy.data.actions: - item = context.scene.psa_action_list.add() - item.action = action - if self.is_action_for_armature(action): - item.is_selected = True - - if len(context.scene.psa_action_list) == 0: - self.report({'ERROR_INVALID_CONTEXT'}, 'There are no actions to export.') - return {'CANCELLED'} - - context.window_manager.fileselect_add(self) - return {'RUNNING_MODAL'} - - def execute(self, context): - actions = [x.action for x in context.scene.psa_action_list if x.is_selected] - - if len(actions) == 0: - self.report({'ERROR_INVALID_CONTEXT'}, 'No actions were selected for export.') - return {'CANCELLED'} - - options = PsaBuilderOptions() - options.actions = actions - builder = PsaBuilder() - psk = builder.build(context, options) - exporter = PsaExporter(psk) - exporter.export(self.filepath) - return {'FINISHED'} - - -class PsaImportOperator(Operator, ImportHelper): - # TODO: list out the actions to be imported - bl_idname = 'import.psa' - bl_label = 'Import' - __doc__ = 'PSA Importer (.psa)' - filename_ext = '.psa' - filter_glob: StringProperty(default='*.psa', options={'HIDDEN'}) - filepath: StringProperty( - name='File Path', - description='File path used for importing the PSA file', - maxlen=1024, - default='') - - def invoke(self, context, event): - action_names = [] - try: - action_names = PsaReader().scan_sequence_names(self.filepath) - except IOError: - pass - - context.scene.psa_import_action_list.clear() - for action_name in action_names: - item = context.scene.psa_action_list.add() - item.action_name = action_name - item.is_selected = True - - context.window_manager.fileselect_add(self) - return {'RUNNING_MODAL'} - - def draw(self, context): - layout = self.layout - scene = context.scene - box = layout.box() - box.label(text='Actions', icon='ACTION') - row = box.row() - row.template_list('PSA_UL_ImportActionList', 'asd', scene, 'psa_import_action_list', scene, 'psa_import_action_list_index', rows=len(context.scene.psa_import_action_list)) - - def execute(self, context): - reader = PsaReader() - psa = reader.read(self.filepath) - PsaImporter().import_psa(psa, context) - return {'FINISHED'} diff --git a/io_export_psk_psa/psa/reader.py b/io_export_psk_psa/psa/reader.py index 8ad2611..badd3c8 100644 --- a/io_export_psk_psa/psa/reader.py +++ b/io_export_psk_psa/psa/reader.py @@ -20,9 +20,6 @@ class PsaReader(object): def scan_sequence_names(self, path) -> List[AnyStr]: sequences = [] with open(path, 'rb') as fp: - if fp.read(8) != b'ANIMINFO': - raise IOError('Unexpected file format') - fp.seek(0, 0) while fp.read(1): fp.seek(-1, 1) section = Section.from_buffer_copy(fp.read(ctypes.sizeof(Section))) @@ -44,9 +41,14 @@ class PsaReader(object): elif section.name == b'BONENAMES': PsaReader.read_types(fp, Psa.Bone, section, psa.bones) elif section.name == b'ANIMINFO': - PsaReader.read_types(fp, Psa.Sequence, section, psa.sequences) + sequences = [] + PsaReader.read_types(fp, Psa.Sequence, section, sequences) + for sequence in sequences: + psa.sequences[sequence.name.decode()] = sequence elif section.name == b'ANIMKEYS': PsaReader.read_types(fp, Psa.Key, section, psa.keys) + elif section.name in [b'SCALEKEYS']: + fp.seek(section.data_size * section.data_count, 1) else: raise RuntimeError(f'Unrecognized section "{section.name}"') return psa diff --git a/io_export_psk_psa/psk/data.py b/io_export_psk_psa/psk/data.py index bfdc82f..ba52a44 100644 --- a/io_export_psk_psa/psk/data.py +++ b/io_export_psk_psa/psk/data.py @@ -36,8 +36,8 @@ class Psk(object): class Face(Structure): _fields_ = [ ('wedge_indices', c_uint16 * 3), - ('material_index', c_int8), - ('aux_material_index', c_int8), + ('material_index', c_uint8), + ('aux_material_index', c_uint8), ('smoothing_groups', c_int32) ] diff --git a/io_export_psk_psa/psk/exporter.py b/io_export_psk_psa/psk/exporter.py index fa45eec..bc90446 100644 --- a/io_export_psk_psa/psk/exporter.py +++ b/io_export_psk_psa/psk/exporter.py @@ -1,8 +1,18 @@ -from typing import Type from .data import * +from .builder import PskBuilder +from typing import Type +from bpy.types import Operator +from bpy_extras.io_utils import ExportHelper +from bpy.props import StringProperty + +MAX_WEDGE_COUNT = 65536 +MAX_POINT_COUNT = 4294967296 +MAX_BONE_COUNT = 256 +MAX_MATERIAL_COUNT = 256 class PskExporter(object): + def __init__(self, psk: Psk): self.psk: Psk = psk @@ -19,27 +29,61 @@ class PskExporter(object): fp.write(datum) def export(self, path: str): + if len(self.psk.wedges) > MAX_WEDGE_COUNT: + raise RuntimeError(f'Number of wedges ({len(self.psk.wedges)}) exceeds limit of {MAX_WEDGE_COUNT}') + if len(self.psk.bones) > MAX_BONE_COUNT: + raise RuntimeError(f'Number of bones ({len(self.psk.bones)}) exceeds limit of {MAX_BONE_COUNT}') + if len(self.psk.points) > MAX_POINT_COUNT: + raise RuntimeError(f'Numbers of vertices ({len(self.psk.points)}) exceeds limit of {MAX_POINT_COUNT}') + if len(self.psk.materials) > MAX_MATERIAL_COUNT: + raise RuntimeError(f'Number of materials ({len(self.psk.materials)}) exceeds limit of {MAX_MATERIAL_COUNT}') + with open(path, 'wb') as fp: self.write_section(fp, b'ACTRHEAD') self.write_section(fp, b'PNTS0000', Vector3, self.psk.points) - # WEDGES - if len(self.psk.wedges) <= 65536: - wedge_type = Psk.Wedge16 - else: - wedge_type = Psk.Wedge32 - wedges = [] for index, w in enumerate(self.psk.wedges): - wedge = wedge_type() + wedge = Psk.Wedge16() wedge.material_index = w.material_index wedge.u = w.u wedge.v = w.v wedge.point_index = w.point_index wedges.append(wedge) - self.write_section(fp, b'VTXW0000', wedge_type, wedges) + self.write_section(fp, b'VTXW0000', Psk.Wedge16, wedges) self.write_section(fp, b'FACE0000', Psk.Face, self.psk.faces) self.write_section(fp, b'MATT0000', Psk.Material, self.psk.materials) self.write_section(fp, b'REFSKELT', Psk.Bone, self.psk.bones) self.write_section(fp, b'RAWWEIGHTS', Psk.Weight, self.psk.weights) + + +class PskExportOperator(Operator, ExportHelper): + bl_idname = 'export.psk' + bl_label = 'Export' + __doc__ = 'PSK Exporter (.psk)' + filename_ext = '.psk' + filter_glob: StringProperty(default='*.psk', options={'HIDDEN'}) + + filepath: StringProperty( + name='File Path', + description='File path used for exporting the PSK file', + maxlen=1024, + default='') + + def invoke(self, context, event): + try: + PskBuilder.get_input_objects(context) + except RuntimeError as e: + self.report({'ERROR_INVALID_CONTEXT'}, str(e)) + return {'CANCELLED'} + + context.window_manager.fileselect_add(self) + return {'RUNNING_MODAL'} + + def execute(self, context): + builder = PskBuilder() + psk = builder.build(context) + exporter = PskExporter(psk) + exporter.export(self.filepath) + return {'FINISHED'} diff --git a/io_export_psk_psa/psk/importer.py b/io_export_psk_psa/psk/importer.py index df2da4b..49ef02a 100644 --- a/io_export_psk_psa/psk/importer.py +++ b/io_export_psk_psa/psk/importer.py @@ -1,17 +1,25 @@ +import os import bpy import bmesh -import mathutils +from typing import Optional from .data import Psk +from mathutils import Quaternion, Vector, Matrix +from .reader import PskReader +from bpy.props import StringProperty +from bpy.types import Operator +from bpy_extras.io_utils import ImportHelper class PskImporter(object): def __init__(self): pass - def import_psk(self, psk: Psk, context): + def import_psk(self, psk: Psk, name: str, context): # ARMATURE - armature_data = bpy.data.armatures.new('armature') - armature_object = bpy.data.objects.new('new_ao', armature_data) + armature_data = bpy.data.armatures.new(name) + armature_object = bpy.data.objects.new(name, armature_data) + armature_object.show_in_front = True + context.scene.collection.objects.link(armature_object) try: @@ -24,19 +32,68 @@ class PskImporter(object): bpy.ops.object.mode_set(mode='EDIT') - for bone in psk.bones: - edit_bone = armature_data.edit_bones.new(bone.name.decode('utf-8')) - edit_bone.parent = armature_data.edit_bones[bone.parent_index] - edit_bone.head = (bone.location.x, bone.location.y, bone.location.z) - rotation = mathutils.Quaternion(*bone.rotation) - edit_bone.tail = edit_bone.head + (mathutils.Vector(0, 0, 1) @ rotation) + # Intermediate bone type for the purpose of construction. + class ImportBone(object): + def __init__(self, index: int, psk_bone: Psk.Bone): + self.index: int = index + self.psk_bone: Psk.Bone = psk_bone + self.parent: Optional[ImportBone] = None + self.local_rotation: Quaternion = Quaternion() + self.local_translation: Vector = Vector() + self.world_rotation_matrix: Matrix = Matrix() + self.world_matrix: Matrix = Matrix() + self.vertex_group = None + + import_bones = [] + should_invert_root = False + new_bone_size = 8.0 + + for bone_index, psk_bone in enumerate(psk.bones): + import_bone = ImportBone(bone_index, psk_bone) + psk_bone.parent_index = max(0, psk_bone.parent_index) + import_bone.local_rotation = Quaternion(tuple(psk_bone.rotation)) + import_bone.local_translation = Vector(tuple(psk_bone.location)) + if psk_bone.parent_index == 0 and bone_index == 0: + if should_invert_root: + import_bone.world_rotation_matrix = import_bone.local_rotation.conjugated().to_matrix() + else: + import_bone.world_rotation_matrix = import_bone.local_rotation.to_matrix() + import_bone.world_matrix = Matrix.Translation(import_bone.local_translation) + import_bones.append(import_bone) + + for bone_index, bone in enumerate(import_bones): + if bone.psk_bone.parent_index == 0 and bone_index == 0: + continue + parent = import_bones[bone.psk_bone.parent_index] + bone.parent = parent + bone.world_matrix = parent.world_rotation_matrix.to_4x4() + translation = bone.local_translation.copy() + translation.rotate(parent.world_rotation_matrix) + bone.world_matrix.translation = parent.world_matrix.translation + translation + bone.world_rotation_matrix = bone.local_rotation.conjugated().to_matrix() + bone.world_rotation_matrix.rotate(parent.world_rotation_matrix) + + for bone in import_bones: + edit_bone = armature_data.edit_bones.new(bone.psk_bone.name.decode('utf-8')) + if bone.parent is not None: + edit_bone.parent = armature_data.edit_bones[bone.psk_bone.parent_index] + elif not should_invert_root: + bone.local_rotation.conjugate() + post_quat = bone.local_rotation.conjugated() + edit_bone.tail = Vector((0.0, new_bone_size, 0.0)) + m = post_quat.copy() + m.rotate(bone.world_matrix) + m = m.to_matrix().to_4x4() + m.translation = bone.world_matrix.translation + edit_bone.matrix = m # MESH - mesh_data = bpy.data.meshes.new('mesh') - mesh_object = bpy.data.objects.new('new_mo', mesh_data) + mesh_data = bpy.data.meshes.new(name) + mesh_object = bpy.data.objects.new(name, mesh_data) # MATERIALS for material in psk.materials: + # TODO: re-use of materials should be an option bpy_material = bpy.data.materials.new(material.name.decode('utf-8')) mesh_data.materials.append(bpy_material) @@ -44,7 +101,7 @@ class PskImporter(object): # VERTICES for point in psk.points: - bm.verts.new((point.x, point.y, point.z)) + bm.verts.new(tuple(point)) bm.verts.ensure_lookup_table() @@ -64,8 +121,47 @@ class PskImporter(object): uv_layer.data[data_index].uv = wedge.u, 1.0 - wedge.v data_index += 1 + bm.normal_update() bm.free() - # TODO: weights (vertex grorups etc.) + # VERTEX WEIGHTS + + # Get a list of all bones that have weights associated with them. + vertex_group_bone_indices = set(map(lambda weight: weight.bone_index, psk.weights)) + for bone_index in sorted(list(vertex_group_bone_indices)): + import_bones[bone_index].vertex_group = mesh_object.vertex_groups.new(name=import_bones[bone_index].psk_bone.name.decode('windows-1252')) + + for weight in psk.weights: + import_bones[weight.bone_index].vertex_group.add((weight.point_index,), weight.weight, 'ADD') + + # Add armature modifier to our mesh object. + armature_modifier = mesh_object.modifiers.new(name='Armature', type='ARMATURE') + armature_modifier.object = armature_object + mesh_object.parent = armature_object context.scene.collection.objects.link(mesh_object) + + try: + bpy.ops.object.mode_set(mode='OBJECT') + except: + pass + + +class PskImportOperator(Operator, ImportHelper): + bl_idname = 'import.psk' + bl_label = 'Export' + __doc__ = 'PSK Importer (.psk)' + filename_ext = '.psk' + filter_glob: StringProperty(default='*.psk', options={'HIDDEN'}) + filepath: StringProperty( + name='File Path', + description='File path used for exporting the PSK file', + maxlen=1024, + default='') + + def execute(self, context): + reader = PskReader() + psk = reader.read(self.filepath) + name = os.path.splitext(os.path.basename(self.filepath))[0] + PskImporter().import_psk(psk, name, context) + return {'FINISHED'} \ No newline at end of file diff --git a/io_export_psk_psa/psk/operator.py b/io_export_psk_psa/psk/operator.py deleted file mode 100644 index 1826550..0000000 --- a/io_export_psk_psa/psk/operator.py +++ /dev/null @@ -1,57 +0,0 @@ -from bpy.types import Operator -from bpy_extras.io_utils import ExportHelper, ImportHelper -from bpy.props import StringProperty, BoolProperty, FloatProperty -from .builder import PskBuilder -from .exporter import PskExporter -from .reader import PskReader -from .importer import PskImporter - - -class PskImportOperator(Operator, ImportHelper): - bl_idname = 'import.psk' - bl_label = 'Export' - __doc__ = 'PSK Importer (.psk)' - filename_ext = '.psk' - filter_glob: StringProperty(default='*.psk', options={'HIDDEN'}) - filepath: StringProperty( - name='File Path', - description='File path used for exporting the PSK file', - maxlen=1024, - default='') - - def execute(self, context): - reader = PskReader() - psk = reader.read(self.filepath) - PskImporter().import_psk(psk, context) - return {'FINISHED'} - - -class PskExportOperator(Operator, ExportHelper): - bl_idname = 'export.psk' - bl_label = 'Export' - __doc__ = 'PSK Exporter (.psk)' - filename_ext = '.psk' - filter_glob: StringProperty(default='*.psk', options={'HIDDEN'}) - - filepath: StringProperty( - name='File Path', - description='File path used for exporting the PSK file', - maxlen=1024, - default='') - - def invoke(self, context, event): - try: - PskBuilder.get_input_objects(context) - except RuntimeError as e: - self.report({'ERROR_INVALID_CONTEXT'}, str(e)) - return {'CANCELLED'} - - context.window_manager.fileselect_add(self) - return {'RUNNING_MODAL'} - - def execute(self, context): - builder = PskBuilder() - psk = builder.build(context) - exporter = PskExporter(psk) - exporter.export(self.filepath) - return {'FINISHED'} From 5607788d1cfa5919c2d3f91dd92f6b0b8996769f Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Fri, 14 Jan 2022 21:04:18 -0800 Subject: [PATCH 03/19] Importing animations now mostly works, though the root bone is messed up. --- io_export_psk_psa/data.py | 6 ++ io_export_psk_psa/psa/data.py | 10 +- io_export_psk_psa/psa/importer.py | 167 +++++++++++++++++++++++------- io_export_psk_psa/psa/reader.py | 74 +++++++++---- io_export_psk_psa/psk/importer.py | 11 +- 5 files changed, 199 insertions(+), 69 deletions(-) diff --git a/io_export_psk_psa/data.py b/io_export_psk_psa/data.py index a9a9a8f..72bb979 100644 --- a/io_export_psk_psa/data.py +++ b/io_export_psk_psa/data.py @@ -13,6 +13,9 @@ class Vector3(Structure): yield self.y yield self.z + def __repr__(self): + return repr(tuple(self)) + class Quaternion(Structure): _fields_ = [ @@ -28,6 +31,9 @@ class Quaternion(Structure): yield self.y yield self.z + def __repr__(self): + return repr(tuple(self)) + class Section(Structure): _fields_ = [ diff --git a/io_export_psk_psa/psa/data.py b/io_export_psk_psa/psa/data.py index b43503c..819d81c 100644 --- a/io_export_psk_psa/psa/data.py +++ b/io_export_psk_psa/psa/data.py @@ -1,9 +1,13 @@ from typing import List, Dict from ..data import * +""" +Note that keys are not stored within the Psa object. +Use the PsaReader::get_sequence_keys to get a the keys for a sequence. +""" + class Psa(object): - class Bone(Structure): _fields_ = [ ('name', c_char * 64), @@ -38,7 +42,9 @@ class Psa(object): ('time', c_float) ] + def __repr__(self) -> str: + return repr((self.location, self.rotation, self.time)) + def __init__(self): self.bones: List[Psa.Bone] = [] self.sequences: Dict[Psa.Sequence] = {} - self.keys: List[Psa.Key] = [] diff --git a/io_export_psk_psa/psa/importer.py b/io_export_psk_psa/psa/importer.py index a3198f6..13be09e 100644 --- a/io_export_psk_psa/psa/importer.py +++ b/io_export_psk_psa/psa/importer.py @@ -1,7 +1,8 @@ import bpy import mathutils +from mathutils import Vector, Quaternion, Matrix from .data import Psa -from typing import List, AnyStr +from typing import List, AnyStr, Optional import bpy from bpy.types import Operator, Action, UIList, PropertyGroup, Panel, Armature from bpy_extras.io_utils import ExportHelper, ImportHelper @@ -13,64 +14,154 @@ class PsaImporter(object): def __init__(self): pass - def import_psa(self, psa: Psa, sequence_names: List[AnyStr], context): + def import_psa(self, psa_reader: PsaReader, sequence_names: List[AnyStr], context): + psa = psa_reader.psa properties = context.scene.psa_import sequences = map(lambda x: psa.sequences[x], sequence_names) - armature_object = properties.armature_object armature_data = armature_object.data + class ImportBone(object): + def __init__(self, psa_bone: Psa.Bone): + self.psa_bone: Psa.Bone = psa_bone + self.parent: Optional[ImportBone] = None + self.armature_bone = None + self.pose_bone = None + self.orig_loc: Vector = Vector() + self.orig_quat: Quaternion = Quaternion() + self.post_quat: Quaternion = Quaternion() + # TODO: this is UGLY, come up with a way to just map indices for these + self.fcurve_quat_w = None + self.fcurve_quat_x = None + self.fcurve_quat_y = None + self.fcurve_quat_z = None + self.fcurve_location_x = None + self.fcurve_location_y = None + self.fcurve_location_z = None + # create an index mapping from bones in the PSA to bones in the target armature. - bone_indices = {} - data_bone_names = [x.name for x in armature_data.bones] - for index, psa_bone in enumerate(psa.bones): - psa_bone_name = psa_bone.name.decode() + psa_to_armature_bone_indices = {} + armature_bone_names = [x.name for x in armature_data.bones] + psa_bone_names = [] + for psa_bone_index, psa_bone in enumerate(psa.bones): + psa_bone_name = psa_bone.name.decode('windows-1252') + psa_bone_names.append(psa_bone_name) try: - bone_indices[index] = data_bone_names.index(psa_bone_name) + psa_to_armature_bone_indices[psa_bone_index] = armature_bone_names.index(psa_bone_name) except ValueError: pass - del data_bone_names + # report if there are missing bones in the target armature + missing_bone_names = set(psa_bone_names).difference(set(armature_bone_names)) + if len(missing_bone_names) > 0: + print(f'The armature object \'{armature_object.name}\' is missing the following bones that exist in the PSA:') + print(list(sorted(missing_bone_names))) + del armature_bone_names + + # Create intermediate bone data for import operations. + import_bones = [] + for psa_bone_index, psa_bone in enumerate(psa.bones): + bone_name = psa_bone.name.decode('windows-1252') + if psa_bone_index not in psa_to_armature_bone_indices: + # PSA bone does not map to armature bone, skip it and leave an empty bone in its place. + import_bones.append(None) + continue + import_bone = ImportBone(psa_bone) + armature_bone = armature_data.bones[bone_name] + import_bone.pose_bone = armature_object.pose.bones[bone_name] + if psa_bone_index > 0: + import_bone.parent = import_bones[psa_bone.parent_index] + # Calculate the original location & rotation of each bone (in world space maybe?) + if import_bone.parent is not None: + import_bone.orig_loc = armature_bone.matrix_local.translation - armature_bone.parent.matrix_local.translation + import_bone.orig_loc.rotate(armature_bone.parent.matrix_local.to_quaternion().conjugated()) + import_bone.orig_quat = armature_bone.matrix_local.to_quaternion() + import_bone.orig_quat.rotate(armature_bone.parent.matrix_local.to_quaternion().conjugated()) + import_bone.orig_quat.conjugate() + else: + import_bone.orig_loc = armature_bone.matrix_local.translation.copy() + import_bone.orig_quat = armature_bone.matrix_local.to_quaternion() + import_bone.post_quat = import_bone.orig_quat.conjugated() + import_bones.append(import_bone) + + # Create and populate the data for new sequences. for sequence in sequences: action = bpy.data.actions.new(name=sequence.name.decode()) - for psa_bone_index, armature_bone_index in bone_indices.items(): - psa_bone = psa.bones[psa_bone_index] + # TODO: problem might be here (yea, we are confused about the ordering of these things!) + for psa_bone_index, armature_bone_index in psa_to_armature_bone_indices.items(): + import_bone = import_bones[psa_bone_index] pose_bone = armature_object.pose.bones[armature_bone_index] # rotation rotation_data_path = pose_bone.path_from_id('rotation_quaternion') - fcurve_quat_w = action.fcurves.new(rotation_data_path, index=0) - fcurve_quat_x = action.fcurves.new(rotation_data_path, index=0) - fcurve_quat_y = action.fcurves.new(rotation_data_path, index=0) - fcurve_quat_z = action.fcurves.new(rotation_data_path, index=0) + import_bone.fcurve_quat_w = action.fcurves.new(rotation_data_path, index=0) + import_bone.fcurve_quat_x = action.fcurves.new(rotation_data_path, index=1) + import_bone.fcurve_quat_y = action.fcurves.new(rotation_data_path, index=2) + import_bone.fcurve_quat_z = action.fcurves.new(rotation_data_path, index=3) # location location_data_path = pose_bone.path_from_id('location') - fcurve_location_x = action.fcurves.new(location_data_path, index=0) - fcurve_location_y = action.fcurves.new(location_data_path, index=1) - fcurve_location_z = action.fcurves.new(location_data_path, index=2) + import_bone.fcurve_location_x = action.fcurves.new(location_data_path, index=0) + import_bone.fcurve_location_y = action.fcurves.new(location_data_path, index=1) + import_bone.fcurve_location_z = action.fcurves.new(location_data_path, index=2) # add keyframes - fcurve_quat_w.keyframe_points.add(sequence.frame_count) - fcurve_quat_x.keyframe_points.add(sequence.frame_count) - fcurve_quat_y.keyframe_points.add(sequence.frame_count) - fcurve_quat_z.keyframe_points.add(sequence.frame_count) - fcurve_location_x.keyframe_points.add(sequence.frame_count) - fcurve_location_y.keyframe_points.add(sequence.frame_count) - fcurve_location_z.keyframe_points.add(sequence.frame_count) + import_bone.fcurve_quat_w.keyframe_points.add(sequence.frame_count) + import_bone.fcurve_quat_x.keyframe_points.add(sequence.frame_count) + import_bone.fcurve_quat_y.keyframe_points.add(sequence.frame_count) + import_bone.fcurve_quat_z.keyframe_points.add(sequence.frame_count) + import_bone.fcurve_location_x.keyframe_points.add(sequence.frame_count) + import_bone.fcurve_location_y.keyframe_points.add(sequence.frame_count) + import_bone.fcurve_location_z.keyframe_points.add(sequence.frame_count) + + fcurve_interpolation = 'LINEAR' + should_invert_root = False + + key_index = 0 + sequence_name = sequence.name.decode('windows-1252') + sequence_keys = psa_reader.get_sequence_keys(sequence_name) - raw_key_index = 0 # ? for frame_index in range(sequence.frame_count): - for psa_bone_index in range(len(psa.bones)): - if psa_bone_index not in bone_indices: + for import_bone in import_bones: + if import_bone is None: # bone does not exist in the armature, skip it - raw_key_index += 1 + key_index += 1 continue - psa_bone = psa.bones[psa_bone_index] - # ... + key_location = Vector(tuple(sequence_keys[key_index].location)) + key_rotation = Quaternion(tuple(sequence_keys[key_index].rotation)) - raw_key_index += 1 + # TODO: what is this doing exactly? + q = import_bone.post_quat.copy() + q.rotate(import_bone.orig_quat) + quat = q + q = import_bone.post_quat.copy() + if import_bone.parent is None and should_invert_root: + q.rotate(import_bone.orig_quat) + else: + q.rotate(key_rotation) + quat.rotate(q.conjugated()) + + loc = key_location - import_bone.orig_loc + loc.rotate(import_bone.post_quat.conjugated()) + + import_bone.fcurve_quat_w.keyframe_points[frame_index].co = frame_index, quat.w + import_bone.fcurve_quat_x.keyframe_points[frame_index].co = frame_index, quat.x + import_bone.fcurve_quat_y.keyframe_points[frame_index].co = frame_index, quat.y + import_bone.fcurve_quat_z.keyframe_points[frame_index].co = frame_index, quat.z + import_bone.fcurve_location_x.keyframe_points[frame_index].co = frame_index, loc.x + import_bone.fcurve_location_y.keyframe_points[frame_index].co = frame_index, loc.y + import_bone.fcurve_location_z.keyframe_points[frame_index].co = frame_index, loc.z + + import_bone.fcurve_quat_w.keyframe_points[frame_index].interpolation = fcurve_interpolation + import_bone.fcurve_quat_x.keyframe_points[frame_index].interpolation = fcurve_interpolation + import_bone.fcurve_quat_y.keyframe_points[frame_index].interpolation = fcurve_interpolation + import_bone.fcurve_quat_z.keyframe_points[frame_index].interpolation = fcurve_interpolation + import_bone.fcurve_location_x.keyframe_points[frame_index].interpolation = fcurve_interpolation + import_bone.fcurve_location_z.keyframe_points[frame_index].interpolation = fcurve_interpolation + import_bone.fcurve_location_z.keyframe_points[frame_index].interpolation = fcurve_interpolation + + key_index += 1 class PsaImportActionListItem(PropertyGroup): @@ -178,9 +269,9 @@ class PsaImportOperator(Operator): bl_label = 'Import' def execute(self, context): - psa = PsaReader().read(context.scene.psa_import.cool_filepath) + psa_reader = PsaReader(context.scene.psa_import.cool_filepath) sequence_names = [x.action_name for x in context.scene.psa_import.action_list if x.is_selected] - PsaImporter().import_psa(psa, sequence_names, context) + PsaImporter().import_psa(psa_reader, sequence_names, context) return {'FINISHED'} @@ -202,14 +293,14 @@ class PsaImportFileSelectOperator(Operator, ImportHelper): def execute(self, context): context.scene.psa_import.cool_filepath = self.filepath # Load the sequence names from the selected file - action_names = [] + sequence_names = [] try: - action_names = PsaReader().scan_sequence_names(self.filepath) + sequence_names = PsaReader.scan_sequence_names(self.filepath) except IOError: pass context.scene.psa_import.action_list.clear() - for action_name in action_names: + for sequence_name in sequence_names: item = context.scene.psa_import.action_list.add() - item.action_name = action_name.decode() + item.action_name = sequence_name.decode('windows-1252') item.is_selected = True return {'FINISHED'} diff --git a/io_export_psk_psa/psa/reader.py b/io_export_psk_psa/psa/reader.py index badd3c8..f127ccd 100644 --- a/io_export_psk_psa/psa/reader.py +++ b/io_export_psk_psa/psa/reader.py @@ -5,8 +5,10 @@ import ctypes class PsaReader(object): - def __init__(self): - pass + def __init__(self, path): + self.keys_data_offset = 0 + self.fp = open(path, 'rb') + self.psa = self._read(self.fp) @staticmethod def read_types(fp, data_class: ctypes.Structure, section: Section, data): @@ -17,7 +19,9 @@ class PsaReader(object): data.append(data_class.from_buffer_copy(buffer, offset)) offset += section.data_size - def scan_sequence_names(self, path) -> List[AnyStr]: + # TODO: this probably isn't actually needed anymore, we can just read it once. + @staticmethod + def scan_sequence_names(path) -> List[AnyStr]: sequences = [] with open(path, 'rb') as fp: while fp.read(1): @@ -30,26 +34,50 @@ class PsaReader(object): fp.seek(section.data_size * section.data_count, 1) return [] - def read(self, path) -> Psa: + def get_sequence_keys(self, sequence_name) -> List[Psa.Key]: + # Set the file reader to the beginning of the keys data + sequence = self.psa.sequences[sequence_name] + data_size = sizeof(Psa.Key) + bone_count = len(self.psa.bones) + buffer_length = data_size * bone_count * sequence.frame_count + print(f'data_size: {data_size}') + print(f'buffer_length: {buffer_length}') + print(f'bone_count: {bone_count}') + print(f'sequence.frame_count: {sequence.frame_count}') + print(f'self.keys_data_offset: {self.keys_data_offset}') + sequence_keys_offset = self.keys_data_offset + (sequence.frame_start_index * bone_count * data_size) + print(f'sequence_keys_offset: {sequence_keys_offset}') + self.fp.seek(sequence_keys_offset, 0) + buffer = self.fp.read(buffer_length) + offset = 0 + keys = [] + for _ in range(sequence.frame_count * bone_count): + key = Psa.Key.from_buffer_copy(buffer, offset) + keys.append(key) + offset += data_size + return keys + + def _read(self, fp) -> Psa: psa = Psa() - with open(path, 'rb') as fp: - while fp.read(1): - fp.seek(-1, 1) - section = Section.from_buffer_copy(fp.read(ctypes.sizeof(Section))) - if section.name == b'ANIMHEAD': - pass - elif section.name == b'BONENAMES': - PsaReader.read_types(fp, Psa.Bone, section, psa.bones) - elif section.name == b'ANIMINFO': - sequences = [] - PsaReader.read_types(fp, Psa.Sequence, section, sequences) - for sequence in sequences: - psa.sequences[sequence.name.decode()] = sequence - elif section.name == b'ANIMKEYS': - PsaReader.read_types(fp, Psa.Key, section, psa.keys) - elif section.name in [b'SCALEKEYS']: - fp.seek(section.data_size * section.data_count, 1) - else: - raise RuntimeError(f'Unrecognized section "{section.name}"') + while fp.read(1): + fp.seek(-1, 1) + section = Section.from_buffer_copy(fp.read(ctypes.sizeof(Section))) + if section.name == b'ANIMHEAD': + pass + elif section.name == b'BONENAMES': + PsaReader.read_types(fp, Psa.Bone, section, psa.bones) + elif section.name == b'ANIMINFO': + sequences = [] + PsaReader.read_types(fp, Psa.Sequence, section, sequences) + for sequence in sequences: + psa.sequences[sequence.name.decode()] = sequence + elif section.name == b'ANIMKEYS': + # Skip keys on this pass. We will keep this file open and read from it as needed. + self.keys_data_offset = fp.tell() + fp.seek(section.data_size * section.data_count, 1) + elif section.name in [b'SCALEKEYS']: + fp.seek(section.data_size * section.data_count, 1) + else: + raise RuntimeError(f'Unrecognized section "{section.name}"') return psa 1 \ No newline at end of file diff --git a/io_export_psk_psa/psk/importer.py b/io_export_psk_psa/psk/importer.py index 49ef02a..19af075 100644 --- a/io_export_psk_psa/psk/importer.py +++ b/io_export_psk_psa/psk/importer.py @@ -79,13 +79,12 @@ class PskImporter(object): edit_bone.parent = armature_data.edit_bones[bone.psk_bone.parent_index] elif not should_invert_root: bone.local_rotation.conjugate() - post_quat = bone.local_rotation.conjugated() edit_bone.tail = Vector((0.0, new_bone_size, 0.0)) - m = post_quat.copy() - m.rotate(bone.world_matrix) - m = m.to_matrix().to_4x4() - m.translation = bone.world_matrix.translation - edit_bone.matrix = m + edit_bone_matrix = bone.local_rotation.conjugated() + edit_bone_matrix.rotate(bone.world_matrix) + edit_bone_matrix = edit_bone_matrix.to_matrix().to_4x4() + edit_bone_matrix.translation = bone.world_matrix.translation + edit_bone.matrix = edit_bone_matrix # MESH mesh_data = bpy.data.meshes.new(name) From 4e625e37d1b1386ff1d1f1f4462ae9c245998457 Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Sat, 15 Jan 2022 20:52:02 -0800 Subject: [PATCH 04/19] Initial working commit for full PSK/PSA import/export cycle. --- io_export_psk_psa/psa/builder.py | 2 +- io_export_psk_psa/psa/data.py | 7 ++-- io_export_psk_psa/psa/exporter.py | 4 +-- io_export_psk_psa/psa/importer.py | 55 +++++++++++++++++-------------- io_export_psk_psa/psk/importer.py | 28 +++++++++++----- 5 files changed, 58 insertions(+), 38 deletions(-) diff --git a/io_export_psk_psa/psa/builder.py b/io_export_psk_psa/psa/builder.py index e1846f9..38f9c47 100644 --- a/io_export_psk_psa/psa/builder.py +++ b/io_export_psk_psa/psa/builder.py @@ -124,6 +124,6 @@ class PsaBuilder(object): sequence.bone_count = len(pose_bones) sequence.track_time = frame_count - psa.sequences.append(sequence) + psa.sequences[action.name] = sequence return psa diff --git a/io_export_psk_psa/psa/data.py b/io_export_psk_psa/psa/data.py index 819d81c..1ebef63 100644 --- a/io_export_psk_psa/psa/data.py +++ b/io_export_psk_psa/psa/data.py @@ -1,4 +1,6 @@ -from typing import List, Dict +import typing +from typing import List +from collections import OrderedDict from ..data import * """ @@ -47,4 +49,5 @@ class Psa(object): def __init__(self): self.bones: List[Psa.Bone] = [] - self.sequences: Dict[Psa.Sequence] = {} + self.sequences: typing.OrderedDict[Psa.Sequence] = OrderedDict() + self.keys: List[Psa.Key] = [] diff --git a/io_export_psk_psa/psa/exporter.py b/io_export_psk_psa/psa/exporter.py index eb81509..57b312b 100644 --- a/io_export_psk_psa/psa/exporter.py +++ b/io_export_psk_psa/psa/exporter.py @@ -29,7 +29,7 @@ class PsaExporter(object): with open(path, 'wb') as fp: self.write_section(fp, b'ANIMHEAD') self.write_section(fp, b'BONENAMES', Psa.Bone, self.psa.bones) - self.write_section(fp, b'ANIMINFO', Psa.Sequence, self.psa.sequences) + self.write_section(fp, b'ANIMINFO', Psa.Sequence, list(self.psa.sequences.values())) self.write_section(fp, b'ANIMKEYS', Psa.Key, self.psa.keys) @@ -70,7 +70,7 @@ class PsaExportOperator(Operator, ExportHelper): box = layout.box() box.label(text='Actions', icon='ACTION') row = box.row() - row.template_list('PSA_UL_ActionList', 'asd', scene, 'psa_export.action_list', scene, 'psa_export.action_list_index', rows=len(context.scene.psa_export.action_list)) + row.template_list('PSA_UL_ActionList', 'asd', scene.psa_export, 'action_list', scene.psa_export, 'action_list_index', rows=10) def is_action_for_armature(self, action): if len(action.fcurves) == 0: diff --git a/io_export_psk_psa/psa/importer.py b/io_export_psk_psa/psa/importer.py index 13be09e..dfe1538 100644 --- a/io_export_psk_psa/psa/importer.py +++ b/io_export_psk_psa/psa/importer.py @@ -60,28 +60,44 @@ class PsaImporter(object): # Create intermediate bone data for import operations. import_bones = [] + import_bones_dict = dict() for psa_bone_index, psa_bone in enumerate(psa.bones): bone_name = psa_bone.name.decode('windows-1252') - if psa_bone_index not in psa_to_armature_bone_indices: + print(bone_name) + if psa_bone_index not in psa_to_armature_bone_indices: # TODO: replace with bone_name in armature_data.bones # PSA bone does not map to armature bone, skip it and leave an empty bone in its place. import_bones.append(None) continue + import_bone = ImportBone(psa_bone) armature_bone = armature_data.bones[bone_name] import_bone.pose_bone = armature_object.pose.bones[bone_name] - if psa_bone_index > 0: - import_bone.parent = import_bones[psa_bone.parent_index] + + if armature_bone.parent is not None: + if armature_bone.parent.name in psa_bone_names: + import_bone.parent = import_bones_dict[armature_bone.parent.name] + else: + import_bone.parent = None + # Calculate the original location & rotation of each bone (in world space maybe?) - if import_bone.parent is not None: - import_bone.orig_loc = armature_bone.matrix_local.translation - armature_bone.parent.matrix_local.translation - import_bone.orig_loc.rotate(armature_bone.parent.matrix_local.to_quaternion().conjugated()) - import_bone.orig_quat = armature_bone.matrix_local.to_quaternion() - import_bone.orig_quat.rotate(armature_bone.parent.matrix_local.to_quaternion().conjugated()) - import_bone.orig_quat.conjugate() + # TODO: check if the armature bones have custom data written to them and use that instead. + if armature_bone.get('orig_quat') is not None: + # TODO: ideally we don't rely on bone auxiliary data like this, the non-aux data path is incorrect (animations are flipped 180) + import_bone.orig_quat = Quaternion(armature_bone['orig_quat']) + import_bone.orig_loc = Vector(armature_bone['orig_loc']) + import_bone.post_quat = Quaternion(armature_bone['post_quat']) else: - import_bone.orig_loc = armature_bone.matrix_local.translation.copy() - import_bone.orig_quat = armature_bone.matrix_local.to_quaternion() - import_bone.post_quat = import_bone.orig_quat.conjugated() + if import_bone.parent is not None: + import_bone.orig_loc = armature_bone.matrix_local.translation - armature_bone.parent.matrix_local.translation + import_bone.orig_loc.rotate(armature_bone.parent.matrix_local.to_quaternion().conjugated()) + import_bone.orig_quat = armature_bone.matrix_local.to_quaternion() + import_bone.orig_quat.rotate(armature_bone.parent.matrix_local.to_quaternion().conjugated()) + import_bone.orig_quat.conjugate() + else: + import_bone.orig_loc = armature_bone.matrix_local.translation.copy() + import_bone.orig_quat = armature_bone.matrix_local.to_quaternion() + import_bone.post_quat = import_bone.orig_quat.conjugated() + import_bones_dict[bone_name] = import_bone import_bones.append(import_bone) # Create and populate the data for new sequences. @@ -114,9 +130,7 @@ class PsaImporter(object): import_bone.fcurve_location_y.keyframe_points.add(sequence.frame_count) import_bone.fcurve_location_z.keyframe_points.add(sequence.frame_count) - fcurve_interpolation = 'LINEAR' should_invert_root = False - key_index = 0 sequence_name = sequence.name.decode('windows-1252') sequence_keys = psa_reader.get_sequence_keys(sequence_name) @@ -131,13 +145,12 @@ class PsaImporter(object): key_location = Vector(tuple(sequence_keys[key_index].location)) key_rotation = Quaternion(tuple(sequence_keys[key_index].rotation)) - # TODO: what is this doing exactly? q = import_bone.post_quat.copy() q.rotate(import_bone.orig_quat) quat = q q = import_bone.post_quat.copy() - if import_bone.parent is None and should_invert_root: - q.rotate(import_bone.orig_quat) + if import_bone.parent is None and not should_invert_root: + q.rotate(key_rotation.conjugated()) else: q.rotate(key_rotation) quat.rotate(q.conjugated()) @@ -153,14 +166,6 @@ class PsaImporter(object): import_bone.fcurve_location_y.keyframe_points[frame_index].co = frame_index, loc.y import_bone.fcurve_location_z.keyframe_points[frame_index].co = frame_index, loc.z - import_bone.fcurve_quat_w.keyframe_points[frame_index].interpolation = fcurve_interpolation - import_bone.fcurve_quat_x.keyframe_points[frame_index].interpolation = fcurve_interpolation - import_bone.fcurve_quat_y.keyframe_points[frame_index].interpolation = fcurve_interpolation - import_bone.fcurve_quat_z.keyframe_points[frame_index].interpolation = fcurve_interpolation - import_bone.fcurve_location_x.keyframe_points[frame_index].interpolation = fcurve_interpolation - import_bone.fcurve_location_z.keyframe_points[frame_index].interpolation = fcurve_interpolation - import_bone.fcurve_location_z.keyframe_points[frame_index].interpolation = fcurve_interpolation - key_index += 1 diff --git a/io_export_psk_psa/psk/importer.py b/io_export_psk_psa/psk/importer.py index 19af075..a124887 100644 --- a/io_export_psk_psa/psk/importer.py +++ b/io_export_psk_psa/psk/importer.py @@ -43,6 +43,9 @@ class PskImporter(object): self.world_rotation_matrix: Matrix = Matrix() self.world_matrix: Matrix = Matrix() self.vertex_group = None + self.orig_quat: Quaternion = Quaternion() + self.orig_loc: Vector = Vector() + self.post_quat: Quaternion = Quaternion() import_bones = [] should_invert_root = False @@ -73,19 +76,28 @@ class PskImporter(object): bone.world_rotation_matrix = bone.local_rotation.conjugated().to_matrix() bone.world_rotation_matrix.rotate(parent.world_rotation_matrix) - for bone in import_bones: - edit_bone = armature_data.edit_bones.new(bone.psk_bone.name.decode('utf-8')) - if bone.parent is not None: - edit_bone.parent = armature_data.edit_bones[bone.psk_bone.parent_index] + for import_bone in import_bones: + bone_name = import_bone.psk_bone.name.decode('utf-8') + edit_bone = armature_data.edit_bones.new(bone_name) + + if import_bone.parent is not None: + edit_bone.parent = armature_data.edit_bones[import_bone.psk_bone.parent_index] elif not should_invert_root: - bone.local_rotation.conjugate() + import_bone.local_rotation.conjugate() + edit_bone.tail = Vector((0.0, new_bone_size, 0.0)) - edit_bone_matrix = bone.local_rotation.conjugated() - edit_bone_matrix.rotate(bone.world_matrix) + edit_bone_matrix = import_bone.local_rotation.conjugated() + edit_bone_matrix.rotate(import_bone.world_matrix) edit_bone_matrix = edit_bone_matrix.to_matrix().to_4x4() - edit_bone_matrix.translation = bone.world_matrix.translation + edit_bone_matrix.translation = import_bone.world_matrix.translation edit_bone.matrix = edit_bone_matrix + # Store bind pose information in the bone's custom properties. + # This information is used when importing animations from PSA files. + edit_bone['orig_quat'] = import_bone.local_rotation + edit_bone['orig_loc'] = import_bone.local_translation + edit_bone['post_quat'] = import_bone.local_rotation.conjugated() + # MESH mesh_data = bpy.data.meshes.new(name) mesh_object = bpy.data.objects.new(name, mesh_data) From c34ebce128e209b65074bec9981844e5263b327d Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Sun, 16 Jan 2022 14:56:48 -0800 Subject: [PATCH 05/19] PSK importer now discards degenerate triangles. --- io_export_psk_psa/psk/importer.py | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/io_export_psk_psa/psk/importer.py b/io_export_psk_psa/psk/importer.py index a124887..f87dd31 100644 --- a/io_export_psk_psa/psk/importer.py +++ b/io_export_psk_psa/psk/importer.py @@ -116,10 +116,17 @@ class PskImporter(object): bm.verts.ensure_lookup_table() - for face in psk.faces: + degenerate_face_indices = set() + for face_index, face in enumerate(psk.faces): point_indices = [bm.verts[psk.wedges[i].point_index] for i in reversed(face.wedge_indices)] - bm_face = bm.faces.new(point_indices) - bm_face.material_index = face.material_index + try: + bm_face = bm.faces.new(point_indices) + bm_face.material_index = face.material_index + except ValueError: + degenerate_face_indices.add(face_index) + pass + + print(f'WARNING: Discarded {len(degenerate_face_indices)} degenerate face(s).') bm.to_mesh(mesh_data) @@ -127,6 +134,8 @@ class PskImporter(object): data_index = 0 uv_layer = mesh_data.uv_layers.new() for face_index, face in enumerate(psk.faces): + if face_index in degenerate_face_indices: + continue face_wedges = [psk.wedges[i] for i in reversed(face.wedge_indices)] for wedge in face_wedges: uv_layer.data[data_index].uv = wedge.u, 1.0 - wedge.v @@ -139,8 +148,8 @@ class PskImporter(object): # Get a list of all bones that have weights associated with them. vertex_group_bone_indices = set(map(lambda weight: weight.bone_index, psk.weights)) - for bone_index in sorted(list(vertex_group_bone_indices)): - import_bones[bone_index].vertex_group = mesh_object.vertex_groups.new(name=import_bones[bone_index].psk_bone.name.decode('windows-1252')) + for import_bone in map(lambda x: import_bones[x], sorted(list(vertex_group_bone_indices))): + import_bone.vertex_group = mesh_object.vertex_groups.new(name=import_bone.psk_bone.name.decode('windows-1252')) for weight in psk.weights: import_bones[weight.bone_index].vertex_group.add((weight.point_index,), weight.weight, 'ADD') From 10e02a84f15147276cac2badbafff90d81a920f8 Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Sun, 16 Jan 2022 18:57:46 -0800 Subject: [PATCH 06/19] * Fixed a bug where animations could fail to import if the order of the PSA bones did not match the DFS-order of the target armature. * Added Select All + Deselect All to PSA export operator --- io_export_psk_psa/__init__.py | 6 ++++-- io_export_psk_psa/psa/exporter.py | 23 +++++++++++++++++++++++ io_export_psk_psa/psa/importer.py | 27 +++++++++++---------------- 3 files changed, 38 insertions(+), 18 deletions(-) diff --git a/io_export_psk_psa/__init__.py b/io_export_psk_psa/__init__.py index 0921161..e15dcd0 100644 --- a/io_export_psk_psa/__init__.py +++ b/io_export_psk_psa/__init__.py @@ -43,17 +43,19 @@ from bpy.props import PointerProperty classes = [ psk_exporter.PskExportOperator, psk_importer.PskImportOperator, - psa_exporter.PsaExportOperator, psa_importer.PsaImportOperator, psa_importer.PsaImportFileSelectOperator, psa_importer.PSA_UL_ActionList, psa_importer.PSA_UL_ImportActionList, - psa_exporter.PsaExportActionListItem, psa_importer.PsaImportActionListItem, psa_importer.PsaImportSelectAll, psa_importer.PsaImportDeselectAll, psa_importer.PSA_PT_ImportPanel, psa_importer.PsaImportPropertyGroup, + psa_exporter.PsaExportOperator, + psa_exporter.PsaExportSelectAll, + psa_exporter.PsaExportDeselectAll, + psa_exporter.PsaExportActionListItem, psa_exporter.PsaExportPropertyGroup, ] diff --git a/io_export_psk_psa/psa/exporter.py b/io_export_psk_psa/psa/exporter.py index 57b312b..ffd662e 100644 --- a/io_export_psk_psa/psa/exporter.py +++ b/io_export_psk_psa/psa/exporter.py @@ -71,6 +71,9 @@ class PsaExportOperator(Operator, ExportHelper): box.label(text='Actions', icon='ACTION') row = box.row() row.template_list('PSA_UL_ActionList', 'asd', scene.psa_export, 'action_list', scene.psa_export, 'action_list_index', rows=10) + row = box.row() + row.operator('psa_export.actions_select_all', text='Select All') + row.operator('psa_export.actions_deselect_all', text='Deselect All') def is_action_for_armature(self, action): if len(action.fcurves) == 0: @@ -120,3 +123,23 @@ class PsaExportOperator(Operator, ExportHelper): exporter = PsaExporter(psa) exporter.export(self.filepath) return {'FINISHED'} + + +class PsaExportSelectAll(bpy.types.Operator): + bl_idname = 'psa_export.actions_select_all' + bl_label = 'Select All' + + def execute(self, context): + for action in context.scene.psa_export.action_list: + action.is_selected = True + return {'FINISHED'} + + +class PsaExportDeselectAll(bpy.types.Operator): + bl_idname = 'psa_export.actions_deselect_all' + bl_label = 'Deselect All' + + def execute(self, context): + for action in context.scene.psa_export.action_list: + action.is_selected = False + return {'FINISHED'} diff --git a/io_export_psk_psa/psa/importer.py b/io_export_psk_psa/psa/importer.py index dfe1538..e779b27 100644 --- a/io_export_psk_psa/psa/importer.py +++ b/io_export_psk_psa/psa/importer.py @@ -61,28 +61,26 @@ class PsaImporter(object): # Create intermediate bone data for import operations. import_bones = [] import_bones_dict = dict() + for psa_bone_index, psa_bone in enumerate(psa.bones): bone_name = psa_bone.name.decode('windows-1252') - print(bone_name) if psa_bone_index not in psa_to_armature_bone_indices: # TODO: replace with bone_name in armature_data.bones # PSA bone does not map to armature bone, skip it and leave an empty bone in its place. import_bones.append(None) continue - import_bone = ImportBone(psa_bone) - armature_bone = armature_data.bones[bone_name] + import_bone.armature_bone = armature_data.bones[bone_name] import_bone.pose_bone = armature_object.pose.bones[bone_name] + import_bones_dict[bone_name] = import_bone + import_bones.append(import_bone) - if armature_bone.parent is not None: - if armature_bone.parent.name in psa_bone_names: - import_bone.parent = import_bones_dict[armature_bone.parent.name] - else: - import_bone.parent = None - - # Calculate the original location & rotation of each bone (in world space maybe?) - # TODO: check if the armature bones have custom data written to them and use that instead. + for import_bone in filter(lambda x: x is not None, import_bones): + armature_bone = import_bone.armature_bone + if armature_bone.parent is not None and armature_bone.parent.name in psa_bone_names: + import_bone.parent = import_bones_dict[armature_bone.parent.name] + # Calculate the original location & rotation of each bone (in world-space maybe?) if armature_bone.get('orig_quat') is not None: - # TODO: ideally we don't rely on bone auxiliary data like this, the non-aux data path is incorrect (animations are flipped 180) + # TODO: ideally we don't rely on bone auxiliary data like this, the non-aux data path is incorrect (animations are flipped 180 around Z) import_bone.orig_quat = Quaternion(armature_bone['orig_quat']) import_bone.orig_loc = Vector(armature_bone['orig_loc']) import_bone.post_quat = Quaternion(armature_bone['post_quat']) @@ -97,16 +95,13 @@ class PsaImporter(object): import_bone.orig_loc = armature_bone.matrix_local.translation.copy() import_bone.orig_quat = armature_bone.matrix_local.to_quaternion() import_bone.post_quat = import_bone.orig_quat.conjugated() - import_bones_dict[bone_name] = import_bone - import_bones.append(import_bone) # Create and populate the data for new sequences. for sequence in sequences: action = bpy.data.actions.new(name=sequence.name.decode()) - # TODO: problem might be here (yea, we are confused about the ordering of these things!) for psa_bone_index, armature_bone_index in psa_to_armature_bone_indices.items(): import_bone = import_bones[psa_bone_index] - pose_bone = armature_object.pose.bones[armature_bone_index] + pose_bone = import_bone.pose_bone # rotation rotation_data_path = pose_bone.path_from_id('rotation_quaternion') From 78837863e2a5bcfce5ba318898749b38efe7fc35 Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Mon, 17 Jan 2022 01:12:06 -0800 Subject: [PATCH 07/19] Added search filtering for PSA export action list --- io_export_psk_psa/__init__.py | 2 +- io_export_psk_psa/psa/exporter.py | 28 ++++++++++++++++++++++++++-- io_export_psk_psa/psa/importer.py | 17 ----------------- 3 files changed, 27 insertions(+), 20 deletions(-) diff --git a/io_export_psk_psa/__init__.py b/io_export_psk_psa/__init__.py index e15dcd0..75c0b89 100644 --- a/io_export_psk_psa/__init__.py +++ b/io_export_psk_psa/__init__.py @@ -45,7 +45,7 @@ classes = [ psk_importer.PskImportOperator, psa_importer.PsaImportOperator, psa_importer.PsaImportFileSelectOperator, - psa_importer.PSA_UL_ActionList, + psa_exporter.PSA_UL_ExportActionList, psa_importer.PSA_UL_ImportActionList, psa_importer.PsaImportActionListItem, psa_importer.PsaImportSelectAll, diff --git a/io_export_psk_psa/psa/exporter.py b/io_export_psk_psa/psa/exporter.py index ffd662e..4bab2d7 100644 --- a/io_export_psk_psa/psa/exporter.py +++ b/io_export_psk_psa/psa/exporter.py @@ -1,5 +1,5 @@ import bpy -from bpy.types import Operator, PropertyGroup, Action +from bpy.types import Operator, PropertyGroup, Action, UIList from bpy.props import CollectionProperty, IntProperty, PointerProperty, StringProperty, BoolProperty from bpy_extras.io_utils import ExportHelper from typing import Type @@ -35,6 +35,7 @@ class PsaExporter(object): class PsaExportActionListItem(PropertyGroup): action: PointerProperty(type=Action) + action_name: StringProperty() is_selected: BoolProperty(default=False) @property @@ -70,7 +71,7 @@ class PsaExportOperator(Operator, ExportHelper): box = layout.box() box.label(text='Actions', icon='ACTION') row = box.row() - row.template_list('PSA_UL_ActionList', 'asd', scene.psa_export, 'action_list', scene.psa_export, 'action_list_index', rows=10) + row.template_list('PSA_UL_ExportActionList', 'asd', scene.psa_export, 'action_list', scene.psa_export, 'action_list_index', rows=10) row = box.row() row.operator('psa_export.actions_select_all', text='Select All') row.operator('psa_export.actions_deselect_all', text='Deselect All') @@ -99,6 +100,7 @@ class PsaExportOperator(Operator, ExportHelper): for action in bpy.data.actions: item = context.scene.psa_export.action_list.add() item.action = action + item.action_name = action.name if self.is_action_for_armature(action): item.is_selected = True @@ -125,6 +127,28 @@ class PsaExportOperator(Operator, ExportHelper): return {'FINISHED'} +class PSA_UL_ExportActionList(UIList): + def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): + layout.alignment = 'LEFT' + layout.prop(item, 'is_selected', icon_only=True) + layout.label(text=item.action_name) + + def filter_items(self, context, data, property): + # TODO: returns two lists, apparently + actions = getattr(data, property) + flt_flags = [] + flt_neworder = [] + if self.filter_name: + flt_flags = bpy.types.UI_UL_list.filter_items_by_name( + self.filter_name, + self.bitflag_filter_item, + actions, + 'action_name', + reverse=self.use_filter_invert + ) + return flt_flags, flt_neworder + + class PsaExportSelectAll(bpy.types.Operator): bl_idname = 'psa_export.actions_select_all' bl_label = 'Select All' diff --git a/io_export_psk_psa/psa/importer.py b/io_export_psk_psa/psa/importer.py index e779b27..a3593ca 100644 --- a/io_export_psk_psa/psa/importer.py +++ b/io_export_psk_psa/psa/importer.py @@ -189,7 +189,6 @@ class PSA_UL_ImportActionList(UIList): layout.label(text=item.action_name) def filter_items(self, context, data, property): - # TODO: returns two lists, apparently actions = getattr(data, property) flt_flags = [] flt_neworder = [] @@ -204,22 +203,6 @@ class PSA_UL_ImportActionList(UIList): return flt_flags, flt_neworder -class PSA_UL_ActionList(UIList): - def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): - layout.alignment = 'LEFT' - layout.prop(item, 'is_selected', icon_only=True) - layout.label(text=item.action.name) - - def filter_items(self, context, data, property): - # TODO: returns two lists, apparently - actions = getattr(data, property) - flt_flags = [] - flt_neworder = [] - if self.filter_name: - flt_flags = bpy.types.UI_UL_list.filter_items_by_name(self.filter_name, self.bitflag_filter_item, actions, 'name', reverse=self.use_filter_invert) - return flt_flags, flt_neworder - - class PsaImportSelectAll(bpy.types.Operator): bl_idname = 'psa_import.actions_select_all' bl_label = 'Select All' From 7fd0c6de813fb65fb0e6627be3dca19fd0499652 Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Tue, 18 Jan 2022 13:21:38 -0800 Subject: [PATCH 08/19] Bone group filtering appears to work correctly now --- io_export_psk_psa/__init__.py | 2 + io_export_psk_psa/psa/builder.py | 69 +++++++++---- io_export_psk_psa/psa/exporter.py | 81 +++++++++++++-- io_export_psk_psa/psa/importer.py | 166 +++++++++++++++++------------- io_export_psk_psa/psa/reader.py | 8 +- io_export_psk_psa/psk/builder.py | 2 +- io_export_psk_psa/psk/importer.py | 11 +- 7 files changed, 226 insertions(+), 113 deletions(-) diff --git a/io_export_psk_psa/__init__.py b/io_export_psk_psa/__init__.py index 75c0b89..10454f1 100644 --- a/io_export_psk_psa/__init__.py +++ b/io_export_psk_psa/__init__.py @@ -46,6 +46,7 @@ classes = [ psa_importer.PsaImportOperator, psa_importer.PsaImportFileSelectOperator, psa_exporter.PSA_UL_ExportActionList, + psa_exporter.PSA_UL_ExportBoneGroupList, psa_importer.PSA_UL_ImportActionList, psa_importer.PsaImportActionListItem, psa_importer.PsaImportSelectAll, @@ -56,6 +57,7 @@ classes = [ psa_exporter.PsaExportSelectAll, psa_exporter.PsaExportDeselectAll, psa_exporter.PsaExportActionListItem, + psa_exporter.PsaExportBoneGroupListItem, psa_exporter.PsaExportPropertyGroup, ] diff --git a/io_export_psk_psa/psa/builder.py b/io_export_psk_psa/psa/builder.py index 38f9c47..0ae9244 100644 --- a/io_export_psk_psa/psa/builder.py +++ b/io_export_psk_psa/psa/builder.py @@ -4,6 +4,8 @@ from .data import * class PsaBuilderOptions(object): def __init__(self): self.actions = [] + self.bone_filter_mode = 'NONE' + self.bone_group_indices = [] # https://git.cth451.me/cth451/blender-addons/blob/master/io_export_unreal_psk_psa.py @@ -12,7 +14,7 @@ class PsaBuilder(object): # TODO: add options in here (selected anims, eg.) pass - def build(self, context, options) -> Psa: + def build(self, context, options: PsaBuilderOptions) -> Psa: object = context.view_layer.objects.active if object.type != 'ARMATURE': @@ -35,28 +37,59 @@ class PsaBuilder(object): pose_bones.sort(key=lambda x: x[0]) pose_bones = [x[1] for x in pose_bones] - for bone in bones: + bone_indices = list(range(len(bones))) + + if options.bone_filter_mode == 'BONE_GROUPS': + # Get a list of the bone indices that are explicitly part of the bone groups we are including. + bone_index_stack = [] + for bone_index, pose_bone in enumerate(pose_bones): + if pose_bone.bone_group_index in options.bone_group_indices: + bone_index_stack.append(bone_index) + + # For each bone that is explicitly being added, recursively walk up the hierarchy and ensure that all of + # those bone indices are also in the list. + bone_indices = set() + while len(bone_index_stack) > 0: + bone_index = bone_index_stack.pop() + bone = bones[bone_index] + if bone.parent is not None: + parent_bone_index = bone_names.index(bone.parent.name) + if parent_bone_index not in bone_indices: + bone_index_stack.append(parent_bone_index) + bone_indices.add(bone_index) + + del bone_names + + # Sort out list of bone indices to be exported. + bone_indices = sorted(list(bone_indices)) + + # The bone lists now contains only the bones that are going to be exported. + bones = [bones[bone_index] for bone_index in bone_indices] + pose_bones = [pose_bones[bone_index] for bone_index in bone_indices] + + for pose_bone in bones: psa_bone = Psa.Bone() - psa_bone.name = bytes(bone.name, encoding='utf-8') - psa_bone.children_count = len(bone.children) + psa_bone.name = bytes(pose_bone.name, encoding='utf-8') try: - psa_bone.parent_index = bones.index(bone.parent) + parent_index = bones.index(pose_bone.parent) + psa_bone.parent_index = parent_index + psa.bones[parent_index].children_count += 1 except ValueError: psa_bone.parent_index = -1 - if bone.parent is not None: - rotation = bone.matrix.to_quaternion() + if pose_bone.parent is not None: + rotation = pose_bone.matrix.to_quaternion() rotation.x = -rotation.x rotation.y = -rotation.y rotation.z = -rotation.z - quat_parent = bone.parent.matrix.to_quaternion().inverted() - parent_head = quat_parent @ bone.parent.head - parent_tail = quat_parent @ bone.parent.tail - location = (parent_tail - parent_head) + bone.head + quat_parent = pose_bone.parent.matrix.to_quaternion().inverted() + parent_head = quat_parent @ pose_bone.parent.head + parent_tail = quat_parent @ pose_bone.parent.tail + location = (parent_tail - parent_head) + pose_bone.head else: - location = armature.matrix_local @ bone.head - rot_matrix = bone.matrix @ armature.matrix_local.to_3x3() + location = armature.matrix_local @ pose_bone.head + rot_matrix = pose_bone.matrix @ armature.matrix_local.to_3x3() rotation = rot_matrix.to_quaternion() psa_bone.location.x = location.x @@ -92,18 +125,18 @@ class PsaBuilder(object): for frame in range(frame_count): context.scene.frame_set(frame_min + frame) - for bone in pose_bones: + for pose_bone in pose_bones: key = Psa.Key() - pose_bone_matrix = bone.matrix + pose_bone_matrix = pose_bone.matrix - if bone.parent is not None: - pose_bone_parent_matrix = bone.parent.matrix + if pose_bone.parent is not None: + pose_bone_parent_matrix = pose_bone.parent.matrix pose_bone_matrix = pose_bone_parent_matrix.inverted() @ pose_bone_matrix location = pose_bone_matrix.to_translation() rotation = pose_bone_matrix.to_quaternion().normalized() - if bone.parent is not None: + if pose_bone.parent is not None: rotation.x = -rotation.x rotation.y = -rotation.y rotation.z = -rotation.z diff --git a/io_export_psk_psa/psa/exporter.py b/io_export_psk_psa/psa/exporter.py index 4bab2d7..587a586 100644 --- a/io_export_psk_psa/psa/exporter.py +++ b/io_export_psk_psa/psa/exporter.py @@ -1,6 +1,6 @@ import bpy -from bpy.types import Operator, PropertyGroup, Action, UIList -from bpy.props import CollectionProperty, IntProperty, PointerProperty, StringProperty, BoolProperty +from bpy.types import Operator, PropertyGroup, Action, UIList, BoneGroup +from bpy.props import CollectionProperty, IntProperty, PointerProperty, StringProperty, BoolProperty, EnumProperty from bpy_extras.io_utils import ExportHelper from typing import Type from .builder import PsaBuilder, PsaBuilderOptions @@ -43,11 +43,28 @@ class PsaExportActionListItem(PropertyGroup): return self.action.name -class PsaExportPropertyGroup(bpy.types.PropertyGroup): +class PsaExportBoneGroupListItem(PropertyGroup): + name: StringProperty() + index: IntProperty() + is_selected: BoolProperty(default=False) + + @property + def name(self): + return self.bone_group.name + + +class PsaExportPropertyGroup(PropertyGroup): action_list: CollectionProperty(type=PsaExportActionListItem) - import_action_list: CollectionProperty(type=PsaExportActionListItem) - action_list_index: IntProperty(name='index for list??', default=0) - import_action_list_index: IntProperty(name='index for list??', default=0) + action_list_index: IntProperty(default=0) + bone_filter_mode: EnumProperty( + name='Bone Filter', + items={ + ('NONE', 'None', 'All bones will be exported.'), + ('BONE_GROUPS', 'Bone Groups', 'Only bones belonging to the selected bone groups will be exported.'), + } + ) + bone_group_list: CollectionProperty(type=PsaExportBoneGroupListItem) + bone_group_list_index: IntProperty(default=0) class PsaExportOperator(Operator, ExportHelper): @@ -68,14 +85,29 @@ class PsaExportOperator(Operator, ExportHelper): def draw(self, context): layout = self.layout scene = context.scene + box = layout.box() box.label(text='Actions', icon='ACTION') + row = box.row() row.template_list('PSA_UL_ExportActionList', 'asd', scene.psa_export, 'action_list', scene.psa_export, 'action_list_index', rows=10) + row = box.row() row.operator('psa_export.actions_select_all', text='Select All') row.operator('psa_export.actions_deselect_all', text='Deselect All') + box = layout.box() + box.label(text='Bone Filter', icon='FILTER') + + row = box.row() + row.alignment = 'EXPAND' + row.prop(scene.psa_export, 'bone_filter_mode', expand=True, text='Bone Filter') + + if scene.psa_export.bone_filter_mode == 'BONE_GROUPS': + row = box.row() + rows = max(3, min(len(scene.psa_export.bone_group_list), 10)) + row.template_list('PSA_UL_ExportBoneGroupList', 'asd', scene.psa_export, 'bone_group_list', scene.psa_export, 'bone_group_list_index', rows=rows) + def is_action_for_armature(self, action): if len(action.fcurves) == 0: return False @@ -90,12 +122,17 @@ class PsaExportOperator(Operator, ExportHelper): return False def invoke(self, context, event): + if context.view_layer.objects.active is None: + self.report({'ERROR_INVALID_CONTEXT'}, 'An armature must be selected') + return {'CANCELLED'} + if context.view_layer.objects.active.type != 'ARMATURE': self.report({'ERROR_INVALID_CONTEXT'}, 'The selected object must be an armature.') return {'CANCELLED'} self.armature = context.view_layer.objects.active + # Populate actions list. context.scene.psa_export.action_list.clear() for action in bpy.data.actions: item = context.scene.psa_export.action_list.add() @@ -105,10 +142,20 @@ class PsaExportOperator(Operator, ExportHelper): item.is_selected = True if len(context.scene.psa_export.action_list) == 0: + # If there are no actions at all, we have nothing to export, so just cancel the operation. self.report({'ERROR_INVALID_CONTEXT'}, 'There are no actions to export.') return {'CANCELLED'} + # Populate bone groups list. + context.scene.psa_export.bone_group_list.clear() + for bone_group_index, bone_group in enumerate(self.armature.pose.bone_groups): + item = context.scene.psa_export.bone_group_list.add() + item.name = bone_group.name + item.index = bone_group_index + item.is_selected = False + context.window_manager.fileselect_add(self) + return {'RUNNING_MODAL'} def execute(self, context): @@ -120,6 +167,8 @@ class PsaExportOperator(Operator, ExportHelper): options = PsaBuilderOptions() options.actions = actions + options.bone_filter_mode = context.scene.psa_export.bone_filter_mode + options.bone_group_indices = [x.index for x in context.scene.psa_export.bone_group_list if x.is_selected] builder = PsaBuilder() psa = builder.build(context, options) exporter = PsaExporter(psa) @@ -127,6 +176,13 @@ class PsaExportOperator(Operator, ExportHelper): return {'FINISHED'} +class PSA_UL_ExportBoneGroupList(UIList): + def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): + layout.alignment = 'LEFT' + layout.prop(item, 'is_selected', icon_only=True) + layout.label(text=item.name, icon='GROUP_BONE') + + class PSA_UL_ExportActionList(UIList): def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): layout.alignment = 'LEFT' @@ -134,7 +190,6 @@ class PSA_UL_ExportActionList(UIList): layout.label(text=item.action_name) def filter_items(self, context, data, property): - # TODO: returns two lists, apparently actions = getattr(data, property) flt_flags = [] flt_neworder = [] @@ -153,6 +208,12 @@ class PsaExportSelectAll(bpy.types.Operator): bl_idname = 'psa_export.actions_select_all' bl_label = 'Select All' + @classmethod + def poll(cls, context): + action_list = context.scene.psa_export.action_list + has_unselected_actions = any(map(lambda action: not action.is_selected, action_list)) + return len(action_list) > 0 and has_unselected_actions + def execute(self, context): for action in context.scene.psa_export.action_list: action.is_selected = True @@ -163,6 +224,12 @@ class PsaExportDeselectAll(bpy.types.Operator): bl_idname = 'psa_export.actions_deselect_all' bl_label = 'Deselect All' + @classmethod + def poll(cls, context): + action_list = context.scene.psa_export.action_list + has_selected_actions = any(map(lambda action: action.is_selected, action_list)) + return len(action_list) > 0 and has_selected_actions + def execute(self, context): for action in context.scene.psa_export.action_list: action.is_selected = False diff --git a/io_export_psk_psa/psa/importer.py b/io_export_psk_psa/psa/importer.py index a3593ca..7848fa8 100644 --- a/io_export_psk_psa/psa/importer.py +++ b/io_export_psk_psa/psa/importer.py @@ -4,10 +4,11 @@ from mathutils import Vector, Quaternion, Matrix from .data import Psa from typing import List, AnyStr, Optional import bpy -from bpy.types import Operator, Action, UIList, PropertyGroup, Panel, Armature +from bpy.types import Operator, Action, UIList, PropertyGroup, Panel, Armature, FileSelectParams from bpy_extras.io_utils import ExportHelper, ImportHelper from bpy.props import StringProperty, BoolProperty, CollectionProperty, PointerProperty, IntProperty from .reader import PsaReader +import numpy as np class PsaImporter(object): @@ -30,14 +31,7 @@ class PsaImporter(object): self.orig_loc: Vector = Vector() self.orig_quat: Quaternion = Quaternion() self.post_quat: Quaternion = Quaternion() - # TODO: this is UGLY, come up with a way to just map indices for these - self.fcurve_quat_w = None - self.fcurve_quat_x = None - self.fcurve_quat_y = None - self.fcurve_quat_z = None - self.fcurve_location_x = None - self.fcurve_location_y = None - self.fcurve_location_z = None + self.fcurves = [] # create an index mapping from bones in the PSA to bones in the target armature. psa_to_armature_bone_indices = {} @@ -103,90 +97,105 @@ class PsaImporter(object): import_bone = import_bones[psa_bone_index] pose_bone = import_bone.pose_bone - # rotation + # create fcurves from rotation and location data rotation_data_path = pose_bone.path_from_id('rotation_quaternion') - import_bone.fcurve_quat_w = action.fcurves.new(rotation_data_path, index=0) - import_bone.fcurve_quat_x = action.fcurves.new(rotation_data_path, index=1) - import_bone.fcurve_quat_y = action.fcurves.new(rotation_data_path, index=2) - import_bone.fcurve_quat_z = action.fcurves.new(rotation_data_path, index=3) - - # location location_data_path = pose_bone.path_from_id('location') - import_bone.fcurve_location_x = action.fcurves.new(location_data_path, index=0) - import_bone.fcurve_location_y = action.fcurves.new(location_data_path, index=1) - import_bone.fcurve_location_z = action.fcurves.new(location_data_path, index=2) + import_bone.fcurves.extend([ + action.fcurves.new(rotation_data_path, index=0), # Qw + action.fcurves.new(rotation_data_path, index=1), # Qx + action.fcurves.new(rotation_data_path, index=2), # Qy + action.fcurves.new(rotation_data_path, index=3), # Qz + action.fcurves.new(location_data_path, index=0), # Lx + action.fcurves.new(location_data_path, index=1), # Ly + action.fcurves.new(location_data_path, index=2), # Lz + ]) - # add keyframes - import_bone.fcurve_quat_w.keyframe_points.add(sequence.frame_count) - import_bone.fcurve_quat_x.keyframe_points.add(sequence.frame_count) - import_bone.fcurve_quat_y.keyframe_points.add(sequence.frame_count) - import_bone.fcurve_quat_z.keyframe_points.add(sequence.frame_count) - import_bone.fcurve_location_x.keyframe_points.add(sequence.frame_count) - import_bone.fcurve_location_y.keyframe_points.add(sequence.frame_count) - import_bone.fcurve_location_z.keyframe_points.add(sequence.frame_count) - - should_invert_root = False key_index = 0 + + # Read the sequence keys from the PSA file. sequence_name = sequence.name.decode('windows-1252') - sequence_keys = psa_reader.get_sequence_keys(sequence_name) + sequence_keys = psa_reader.read_sequence_keys(sequence_name) for frame_index in range(sequence.frame_count): - for import_bone in import_bones: + for bone_index, import_bone in enumerate(import_bones): if import_bone is None: # bone does not exist in the armature, skip it key_index += 1 continue - key_location = Vector(tuple(sequence_keys[key_index].location)) + # Convert world-space transforms to local-space transforms. key_rotation = Quaternion(tuple(sequence_keys[key_index].rotation)) - q = import_bone.post_quat.copy() q.rotate(import_bone.orig_quat) quat = q q = import_bone.post_quat.copy() - if import_bone.parent is None and not should_invert_root: + if import_bone.parent is None: q.rotate(key_rotation.conjugated()) else: q.rotate(key_rotation) quat.rotate(q.conjugated()) + key_location = Vector(tuple(sequence_keys[key_index].location)) loc = key_location - import_bone.orig_loc loc.rotate(import_bone.post_quat.conjugated()) - import_bone.fcurve_quat_w.keyframe_points[frame_index].co = frame_index, quat.w - import_bone.fcurve_quat_x.keyframe_points[frame_index].co = frame_index, quat.x - import_bone.fcurve_quat_y.keyframe_points[frame_index].co = frame_index, quat.y - import_bone.fcurve_quat_z.keyframe_points[frame_index].co = frame_index, quat.z - import_bone.fcurve_location_x.keyframe_points[frame_index].co = frame_index, loc.x - import_bone.fcurve_location_y.keyframe_points[frame_index].co = frame_index, loc.y - import_bone.fcurve_location_z.keyframe_points[frame_index].co = frame_index, loc.z + bone_fcurve_data = quat.w, quat.x, quat.y, quat.z, loc.x, loc.y, loc.z + for fcurve, datum in zip(import_bone.fcurves, bone_fcurve_data): + fcurve.keyframe_points.insert(frame_index, datum) key_index += 1 class PsaImportActionListItem(PropertyGroup): action_name: StringProperty() - is_selected: BoolProperty(default=True) + frame_count: IntProperty() + is_selected: BoolProperty(default=False) @property def name(self): return self.action_name +def on_psa_filepath_updated(property, context): + context.scene.psa_import.action_list.clear() + try: + # Read the file and populate the action list. + psa = PsaReader(context.scene.psa_import.psa_filepath).psa + for sequence in psa.sequences.values(): + item = context.scene.psa_import.action_list.add() + item.action_name = sequence.name.decode('windows-1252') + item.frame_count = sequence.frame_count + item.is_selected = True + except IOError: + # TODO: set an error somewhere so the user knows the PSA could not be read. + pass + + class PsaImportPropertyGroup(bpy.types.PropertyGroup): - cool_filepath: StringProperty(default='') - armature_object: PointerProperty(type=bpy.types.Object) # TODO: figure out how to filter this to only objects of a specific type + psa_filepath: StringProperty(default='', subtype='FILE_PATH', update=on_psa_filepath_updated) + armature_object: PointerProperty(name='Armature', type=bpy.types.Object) action_list: CollectionProperty(type=PsaImportActionListItem) - import_action_list: CollectionProperty(type=PsaImportActionListItem) - action_list_index: IntProperty(name='index for list??', default=0) - import_action_list_index: IntProperty(name='index for list??', default=0) + action_list_index: IntProperty(name='', default=0) + action_filter_name: StringProperty(default='') class PSA_UL_ImportActionList(UIList): + def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): - layout.alignment = 'LEFT' - layout.prop(item, 'is_selected', icon_only=True) - layout.label(text=item.action_name) + row = layout.row(align=True) + split = row.split(align=True, factor=0.75) + action_col = split.row(align=True) + action_col.alignment = 'LEFT' + action_col.prop(item, 'is_selected', icon_only=True) + action_col.label(text=item.action_name) + + def draw_filter(self, context, layout): + row = layout.row() + subrow = row.row(align=True) + subrow.prop(self, 'filter_name', text="") + subrow.prop(self, 'use_filter_invert', text="", icon='ARROW_LEFTRIGHT') + subrow = row.row(align=True) + subrow.prop(self, 'use_filter_sort_reverse', text='', icon='SORT_ASC') def filter_items(self, context, data, property): actions = getattr(data, property) @@ -205,7 +214,13 @@ class PSA_UL_ImportActionList(UIList): class PsaImportSelectAll(bpy.types.Operator): bl_idname = 'psa_import.actions_select_all' - bl_label = 'Select All' + bl_label = 'All' + + @classmethod + def poll(cls, context): + action_list = context.scene.psa_import.action_list + has_unselected_actions = any(map(lambda action: not action.is_selected, action_list)) + return len(action_list) > 0 and has_unselected_actions def execute(self, context): for action in context.scene.psa_import.action_list: @@ -215,7 +230,13 @@ class PsaImportSelectAll(bpy.types.Operator): class PsaImportDeselectAll(bpy.types.Operator): bl_idname = 'psa_import.actions_deselect_all' - bl_label = 'Deselect All' + bl_label = 'None' + + @classmethod + def poll(cls, context): + action_list = context.scene.psa_import.action_list + has_selected_actions = any(map(lambda action: action.is_selected, action_list)) + return len(action_list) > 0 and has_selected_actions def execute(self, context): for action in context.scene.psa_import.action_list: @@ -234,25 +255,34 @@ class PSA_PT_ImportPanel(Panel): layout = self.layout scene = context.scene row = layout.row() - row.operator('psa_import.file_select', icon='FILE_FOLDER', text='') - row.label(text=scene.psa_import.cool_filepath) + row.prop(scene.psa_import, 'psa_filepath', text='PSA File') + row = layout.row() + row.prop_search(scene.psa_import, 'armature_object', bpy.data, 'objects') box = layout.box() - box.label(text='Actions', icon='ACTION') + box.label(text=f'Actions ({len(scene.psa_import.action_list)})', icon='ACTION') row = box.row() - row.template_list('PSA_UL_ImportActionList', 'asd', scene.psa_import, 'action_list', scene.psa_import, 'action_list_index', rows=10) - row = box.row() - row.operator('psa_import.actions_select_all', text='Select All') - row.operator('psa_import.actions_deselect_all', text='Deselect All') - layout.prop(scene.psa_import, 'armature_object', icon_only=True) - layout.operator('psa_import.import', text='Import') + rows = max(3, min(len(scene.psa_import.action_list), 10)) + row.template_list('PSA_UL_ImportActionList', 'asd', scene.psa_import, 'action_list', scene.psa_import, 'action_list_index', rows=rows) + row = box.row(align=True) + row.label(text='Select') + row.operator('psa_import.actions_select_all', text='All') + row.operator('psa_import.actions_deselect_all', text='None') + layout.operator('psa_import.import', text=f'Import') class PsaImportOperator(Operator): bl_idname = 'psa_import.import' bl_label = 'Import' + @classmethod + def poll(cls, context): + action_list = context.scene.psa_import.action_list + has_selected_actions = any(map(lambda action: action.is_selected, action_list)) + armature_object = context.scene.psa_import.armature_object + return has_selected_actions and armature_object is not None + def execute(self, context): - psa_reader = PsaReader(context.scene.psa_import.cool_filepath) + psa_reader = PsaReader(context.scene.psa_import.psa_filepath) sequence_names = [x.action_name for x in context.scene.psa_import.action_list if x.is_selected] PsaImporter().import_psa(psa_reader, sequence_names, context) return {'FINISHED'} @@ -274,16 +304,6 @@ class PsaImportFileSelectOperator(Operator, ImportHelper): return {'RUNNING_MODAL'} def execute(self, context): - context.scene.psa_import.cool_filepath = self.filepath + context.scene.psa_import.psa_filepath = self.filepath # Load the sequence names from the selected file - sequence_names = [] - try: - sequence_names = PsaReader.scan_sequence_names(self.filepath) - except IOError: - pass - context.scene.psa_import.action_list.clear() - for sequence_name in sequence_names: - item = context.scene.psa_import.action_list.add() - item.action_name = sequence_name.decode('windows-1252') - item.is_selected = True return {'FINISHED'} diff --git a/io_export_psk_psa/psa/reader.py b/io_export_psk_psa/psa/reader.py index f127ccd..2f01c19 100644 --- a/io_export_psk_psa/psa/reader.py +++ b/io_export_psk_psa/psa/reader.py @@ -34,19 +34,13 @@ class PsaReader(object): fp.seek(section.data_size * section.data_count, 1) return [] - def get_sequence_keys(self, sequence_name) -> List[Psa.Key]: + def read_sequence_keys(self, sequence_name) -> List[Psa.Key]: # Set the file reader to the beginning of the keys data sequence = self.psa.sequences[sequence_name] data_size = sizeof(Psa.Key) bone_count = len(self.psa.bones) buffer_length = data_size * bone_count * sequence.frame_count - print(f'data_size: {data_size}') - print(f'buffer_length: {buffer_length}') - print(f'bone_count: {bone_count}') - print(f'sequence.frame_count: {sequence.frame_count}') - print(f'self.keys_data_offset: {self.keys_data_offset}') sequence_keys_offset = self.keys_data_offset + (sequence.frame_start_index * bone_count * data_size) - print(f'sequence_keys_offset: {sequence_keys_offset}') self.fp.seek(sequence_keys_offset, 0) buffer = self.fp.read(buffer_length) offset = 0 diff --git a/io_export_psk_psa/psk/builder.py b/io_export_psk_psa/psk/builder.py index 2cc82fb..c5d92a0 100644 --- a/io_export_psk_psa/psk/builder.py +++ b/io_export_psk_psa/psk/builder.py @@ -40,7 +40,7 @@ class PskBuilder(object): modifiers = [x for x in obj.modifiers if x.type == 'ARMATURE'] if len(modifiers) == 0: continue - elif len(modifiers) == 2: + elif len(modifiers) > 1: raise RuntimeError(f'Mesh "{obj.name}" must have only one armature modifier') armature_modifier_objects.add(modifiers[0].object) diff --git a/io_export_psk_psa/psk/importer.py b/io_export_psk_psa/psk/importer.py index f87dd31..1de4c7c 100644 --- a/io_export_psk_psa/psk/importer.py +++ b/io_export_psk_psa/psk/importer.py @@ -48,7 +48,6 @@ class PskImporter(object): self.post_quat: Quaternion = Quaternion() import_bones = [] - should_invert_root = False new_bone_size = 8.0 for bone_index, psk_bone in enumerate(psk.bones): @@ -57,10 +56,7 @@ class PskImporter(object): import_bone.local_rotation = Quaternion(tuple(psk_bone.rotation)) import_bone.local_translation = Vector(tuple(psk_bone.location)) if psk_bone.parent_index == 0 and bone_index == 0: - if should_invert_root: - import_bone.world_rotation_matrix = import_bone.local_rotation.conjugated().to_matrix() - else: - import_bone.world_rotation_matrix = import_bone.local_rotation.to_matrix() + import_bone.world_rotation_matrix = import_bone.local_rotation.to_matrix() import_bone.world_matrix = Matrix.Translation(import_bone.local_translation) import_bones.append(import_bone) @@ -82,7 +78,7 @@ class PskImporter(object): if import_bone.parent is not None: edit_bone.parent = armature_data.edit_bones[import_bone.psk_bone.parent_index] - elif not should_invert_root: + else: import_bone.local_rotation.conjugate() edit_bone.tail = Vector((0.0, new_bone_size, 0.0)) @@ -126,7 +122,8 @@ class PskImporter(object): degenerate_face_indices.add(face_index) pass - print(f'WARNING: Discarded {len(degenerate_face_indices)} degenerate face(s).') + if len(degenerate_face_indices) > 0: + print(f'WARNING: Discarded {len(degenerate_face_indices)} degenerate face(s).') bm.to_mesh(mesh_data) From 728f70a356130fb808c521d8044bf5acecc6e1d0 Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Tue, 18 Jan 2022 16:06:54 -0800 Subject: [PATCH 09/19] Fixed a bug where animations would be incorrectly imported. --- io_export_psk_psa/psa/importer.py | 56 +++++++++++++++++-------------- io_export_psk_psa/psa/reader.py | 45 +++++++++++++------------ 2 files changed, 54 insertions(+), 47 deletions(-) diff --git a/io_export_psk_psa/psa/importer.py b/io_export_psk_psa/psa/importer.py index 7848fa8..1b75732 100644 --- a/io_export_psk_psa/psa/importer.py +++ b/io_export_psk_psa/psa/importer.py @@ -1,14 +1,12 @@ import bpy -import mathutils +import os from mathutils import Vector, Quaternion, Matrix from .data import Psa from typing import List, AnyStr, Optional -import bpy from bpy.types import Operator, Action, UIList, PropertyGroup, Panel, Armature, FileSelectParams from bpy_extras.io_utils import ExportHelper, ImportHelper from bpy.props import StringProperty, BoolProperty, CollectionProperty, PointerProperty, IntProperty from .reader import PsaReader -import numpy as np class PsaImporter(object): @@ -16,9 +14,8 @@ class PsaImporter(object): pass def import_psa(self, psa_reader: PsaReader, sequence_names: List[AnyStr], context): - psa = psa_reader.psa properties = context.scene.psa_import - sequences = map(lambda x: psa.sequences[x], sequence_names) + sequences = map(lambda x: psa_reader.sequences[x], sequence_names) armature_object = properties.armature_object armature_data = armature_object.data @@ -33,11 +30,11 @@ class PsaImporter(object): self.post_quat: Quaternion = Quaternion() self.fcurves = [] - # create an index mapping from bones in the PSA to bones in the target armature. + # Create an index mapping from bones in the PSA to bones in the target armature. psa_to_armature_bone_indices = {} armature_bone_names = [x.name for x in armature_data.bones] psa_bone_names = [] - for psa_bone_index, psa_bone in enumerate(psa.bones): + for psa_bone_index, psa_bone in enumerate(psa_reader.bones): psa_bone_name = psa_bone.name.decode('windows-1252') psa_bone_names.append(psa_bone_name) try: @@ -45,7 +42,7 @@ class PsaImporter(object): except ValueError: pass - # report if there are missing bones in the target armature + # Report if there are missing bones in the target armature. missing_bone_names = set(psa_bone_names).difference(set(armature_bone_names)) if len(missing_bone_names) > 0: print(f'The armature object \'{armature_object.name}\' is missing the following bones that exist in the PSA:') @@ -56,7 +53,7 @@ class PsaImporter(object): import_bones = [] import_bones_dict = dict() - for psa_bone_index, psa_bone in enumerate(psa.bones): + for psa_bone_index, psa_bone in enumerate(psa_reader.bones): bone_name = psa_bone.name.decode('windows-1252') if psa_bone_index not in psa_to_armature_bone_indices: # TODO: replace with bone_name in armature_data.bones # PSA bone does not map to armature bone, skip it and leave an empty bone in its place. @@ -93,14 +90,14 @@ class PsaImporter(object): # Create and populate the data for new sequences. for sequence in sequences: action = bpy.data.actions.new(name=sequence.name.decode()) + + # Create f-curves for the rotation and location of each bone. for psa_bone_index, armature_bone_index in psa_to_armature_bone_indices.items(): import_bone = import_bones[psa_bone_index] pose_bone = import_bone.pose_bone - - # create fcurves from rotation and location data rotation_data_path = pose_bone.path_from_id('rotation_quaternion') location_data_path = pose_bone.path_from_id('location') - import_bone.fcurves.extend([ + import_bone.fcurves = [ action.fcurves.new(rotation_data_path, index=0), # Qw action.fcurves.new(rotation_data_path, index=1), # Qx action.fcurves.new(rotation_data_path, index=2), # Qy @@ -108,14 +105,14 @@ class PsaImporter(object): action.fcurves.new(location_data_path, index=0), # Lx action.fcurves.new(location_data_path, index=1), # Ly action.fcurves.new(location_data_path, index=2), # Lz - ]) - - key_index = 0 + ] # Read the sequence keys from the PSA file. sequence_name = sequence.name.decode('windows-1252') sequence_keys = psa_reader.read_sequence_keys(sequence_name) + # Add keyframes for each frame of the sequence. + key_index = 0 for frame_index in range(sequence.frame_count): for bone_index, import_bone in enumerate(import_bones): if import_bone is None: @@ -134,17 +131,22 @@ class PsaImporter(object): else: q.rotate(key_rotation) quat.rotate(q.conjugated()) - key_location = Vector(tuple(sequence_keys[key_index].location)) loc = key_location - import_bone.orig_loc loc.rotate(import_bone.post_quat.conjugated()) + # Add keyframe data for each of the associated f-curves. bone_fcurve_data = quat.w, quat.x, quat.y, quat.z, loc.x, loc.y, loc.z for fcurve, datum in zip(import_bone.fcurves, bone_fcurve_data): - fcurve.keyframe_points.insert(frame_index, datum) + fcurve.keyframe_points.insert(frame_index, datum, options={'FAST'}) key_index += 1 + # Explicitly update the f-curves. + for import_bone in filter(lambda x: x is not None, import_bones): + for fcurve in import_bone.fcurves: + fcurve.update() + class PsaImportActionListItem(PropertyGroup): action_name: StringProperty() @@ -156,23 +158,27 @@ class PsaImportActionListItem(PropertyGroup): return self.action_name -def on_psa_filepath_updated(property, context): +def on_psa_file_path_updated(property, context): context.scene.psa_import.action_list.clear() try: # Read the file and populate the action list. - psa = PsaReader(context.scene.psa_import.psa_filepath).psa - for sequence in psa.sequences.values(): + p = os.path.abspath(context.scene.psa_import.psa_file_path) + print(p) + psa_reader = PsaReader(p) + for sequence in psa_reader.sequences.values(): item = context.scene.psa_import.action_list.add() item.action_name = sequence.name.decode('windows-1252') item.frame_count = sequence.frame_count item.is_selected = True - except IOError: + except IOError as e: + print('ERROR READING FILE') + print(e) # TODO: set an error somewhere so the user knows the PSA could not be read. pass class PsaImportPropertyGroup(bpy.types.PropertyGroup): - psa_filepath: StringProperty(default='', subtype='FILE_PATH', update=on_psa_filepath_updated) + psa_file_path: StringProperty(default='', subtype='FILE_PATH', update=on_psa_file_path_updated) armature_object: PointerProperty(name='Armature', type=bpy.types.Object) action_list: CollectionProperty(type=PsaImportActionListItem) action_list_index: IntProperty(name='', default=0) @@ -255,7 +261,7 @@ class PSA_PT_ImportPanel(Panel): layout = self.layout scene = context.scene row = layout.row() - row.prop(scene.psa_import, 'psa_filepath', text='PSA File') + row.prop(scene.psa_import, 'psa_file_path', text='PSA File') row = layout.row() row.prop_search(scene.psa_import, 'armature_object', bpy.data, 'objects') box = layout.box() @@ -282,7 +288,7 @@ class PsaImportOperator(Operator): return has_selected_actions and armature_object is not None def execute(self, context): - psa_reader = PsaReader(context.scene.psa_import.psa_filepath) + psa_reader = PsaReader(context.scene.psa_import.psa_file_path) sequence_names = [x.action_name for x in context.scene.psa_import.action_list if x.is_selected] PsaImporter().import_psa(psa_reader, sequence_names, context) return {'FINISHED'} @@ -304,6 +310,6 @@ class PsaImportFileSelectOperator(Operator, ImportHelper): return {'RUNNING_MODAL'} def execute(self, context): - context.scene.psa_import.psa_filepath = self.filepath + context.scene.psa_import.psa_file_path = self.filepath # Load the sequence names from the selected file return {'FINISHED'} diff --git a/io_export_psk_psa/psa/reader.py b/io_export_psk_psa/psa/reader.py index 2f01c19..ee99e59 100644 --- a/io_export_psk_psa/psa/reader.py +++ b/io_export_psk_psa/psa/reader.py @@ -1,17 +1,28 @@ from .data import * -from typing import AnyStr import ctypes class PsaReader(object): - + """ + This class will read the sequences and bone information immediately upon instantiation and hold onto a file handle. + The key data is not read into memory upon instantiation due to it's potentially very large size. + To read the key data for a particular sequence, call `read_sequence_keys`. + """ def __init__(self, path): - self.keys_data_offset = 0 + self.keys_data_offset: int = 0 self.fp = open(path, 'rb') - self.psa = self._read(self.fp) + self.psa: Psa = self._read(self.fp) + + @property + def bones(self): + return self.psa.bones + + @property + def sequences(self): + return self.psa.sequences @staticmethod - def read_types(fp, data_class: ctypes.Structure, section: Section, data): + def _read_types(fp, data_class: ctypes.Structure, section: Section, data): buffer_length = section.data_size * section.data_count buffer = fp.read(buffer_length) offset = 0 @@ -19,22 +30,12 @@ class PsaReader(object): data.append(data_class.from_buffer_copy(buffer, offset)) offset += section.data_size - # TODO: this probably isn't actually needed anymore, we can just read it once. - @staticmethod - def scan_sequence_names(path) -> List[AnyStr]: - sequences = [] - with open(path, 'rb') as fp: - while fp.read(1): - fp.seek(-1, 1) - section = Section.from_buffer_copy(fp.read(ctypes.sizeof(Section))) - if section.name == b'ANIMINFO': - PsaReader.read_types(fp, Psa.Sequence, section, sequences) - return [sequence.name for sequence in sequences] - else: - fp.seek(section.data_size * section.data_count, 1) - return [] - def read_sequence_keys(self, sequence_name) -> List[Psa.Key]: + """ Reads and returns the key data for a sequence. + + :param sequence_name: The name of the sequence. + :return: A list of Psa.Keys. + """ # Set the file reader to the beginning of the keys data sequence = self.psa.sequences[sequence_name] data_size = sizeof(Psa.Key) @@ -59,10 +60,10 @@ class PsaReader(object): if section.name == b'ANIMHEAD': pass elif section.name == b'BONENAMES': - PsaReader.read_types(fp, Psa.Bone, section, psa.bones) + PsaReader._read_types(fp, Psa.Bone, section, psa.bones) elif section.name == b'ANIMINFO': sequences = [] - PsaReader.read_types(fp, Psa.Sequence, section, sequences) + PsaReader._read_types(fp, Psa.Sequence, section, sequences) for sequence in sequences: psa.sequences[sequence.name.decode()] = sequence elif section.name == b'ANIMKEYS': From f2ad61ce842413a801c414fc7cddc4db2fdfd0ae Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Tue, 18 Jan 2022 17:41:35 -0800 Subject: [PATCH 10/19] PSA import operations now take dramatically less time to complete. --- io_export_psk_psa/psa/importer.py | 51 ++++++++++++++++++++++++++----- 1 file changed, 43 insertions(+), 8 deletions(-) diff --git a/io_export_psk_psa/psa/importer.py b/io_export_psk_psa/psa/importer.py index 1b75732..39fd8e3 100644 --- a/io_export_psk_psa/psa/importer.py +++ b/io_export_psk_psa/psa/importer.py @@ -1,5 +1,7 @@ import bpy import os +from math import inf +import numpy as np from mathutils import Vector, Quaternion, Matrix from .data import Psa from typing import List, AnyStr, Optional @@ -7,6 +9,7 @@ from bpy.types import Operator, Action, UIList, PropertyGroup, Panel, Armature, from bpy_extras.io_utils import ExportHelper, ImportHelper from bpy.props import StringProperty, BoolProperty, CollectionProperty, PointerProperty, IntProperty from .reader import PsaReader +import datetime class PsaImporter(object): @@ -87,8 +90,16 @@ class PsaImporter(object): import_bone.orig_quat = armature_bone.matrix_local.to_quaternion() import_bone.post_quat = import_bone.orig_quat.conjugated() + io_time = datetime.timedelta() + math_time = datetime.timedelta() + keyframe_time = datetime.timedelta() + # Create and populate the data for new sequences. for sequence in sequences: + # F-curve data buffer for all bones. This is used later on to avoid adding redundant keyframes. + next_frame_bones_fcurve_data = [(inf, inf, inf, inf, inf, inf, inf)] * len(import_bones) + + # Add the action. action = bpy.data.actions.new(name=sequence.name.decode()) # Create f-curves for the rotation and location of each bone. @@ -109,17 +120,21 @@ class PsaImporter(object): # Read the sequence keys from the PSA file. sequence_name = sequence.name.decode('windows-1252') + + now = datetime.datetime.now() sequence_keys = psa_reader.read_sequence_keys(sequence_name) + io_time += datetime.datetime.now() - now # Add keyframes for each frame of the sequence. - key_index = 0 - for frame_index in range(sequence.frame_count): + for frame_index in reversed(range(sequence.frame_count)): + key_index = frame_index * len(import_bones) for bone_index, import_bone in enumerate(import_bones): if import_bone is None: # bone does not exist in the armature, skip it key_index += 1 continue + now = datetime.datetime.now() # Convert world-space transforms to local-space transforms. key_rotation = Quaternion(tuple(sequence_keys[key_index].rotation)) q = import_bone.post_quat.copy() @@ -134,18 +149,38 @@ class PsaImporter(object): key_location = Vector(tuple(sequence_keys[key_index].location)) loc = key_location - import_bone.orig_loc loc.rotate(import_bone.post_quat.conjugated()) + math_time += datetime.datetime.now() - now + now = datetime.datetime.now() # Add keyframe data for each of the associated f-curves. bone_fcurve_data = quat.w, quat.x, quat.y, quat.z, loc.x, loc.y, loc.z - for fcurve, datum in zip(import_bone.fcurves, bone_fcurve_data): - fcurve.keyframe_points.insert(frame_index, datum, options={'FAST'}) + if frame_index == 0: + # Always add a keyframe on the first frame. + for fcurve, datum in zip(import_bone.fcurves, bone_fcurve_data): + fcurve.keyframe_points.insert(frame_index, datum, options={'FAST'}) + else: + # For each f-curve, check that the next frame has data that differs from the current frame. + # If so, add a keyframe for the current frame. + # Note that we are iterating the frames in reverse order. + threshold = 0.001 + for fcurve, datum, old_datum in zip(import_bone.fcurves, bone_fcurve_data, next_frame_bones_fcurve_data[bone_index]): + # Only + if abs(datum - old_datum) > threshold: + fcurve.keyframe_points.insert(frame_index, datum, options={'FAST'}) + + next_frame_bones_fcurve_data[bone_index] = bone_fcurve_data + + keyframe_time += datetime.datetime.now() - now key_index += 1 - # Explicitly update the f-curves. - for import_bone in filter(lambda x: x is not None, import_bones): - for fcurve in import_bone.fcurves: - fcurve.update() + # TODO: eliminate last keyframe if there are only two keyframes (beginning + end and the values are identical) + # in this way, we will effectively have cleaned the keyframes inline. + pass + + print(f'io_time: {io_time}') + print(f'math_time: {math_time}') + print(f'keyframe_time: {keyframe_time}') class PsaImportActionListItem(PropertyGroup): From 59af9d21453b2ca2488ca70cd2e15b50f6ccc4d8 Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Tue, 18 Jan 2022 20:09:53 -0800 Subject: [PATCH 11/19] Now eliminating redundant final keyframes on PSA import. --- io_export_psk_psa/psa/importer.py | 24 ++++++------------------ 1 file changed, 6 insertions(+), 18 deletions(-) diff --git a/io_export_psk_psa/psa/importer.py b/io_export_psk_psa/psa/importer.py index 39fd8e3..37a425c 100644 --- a/io_export_psk_psa/psa/importer.py +++ b/io_export_psk_psa/psa/importer.py @@ -90,10 +90,6 @@ class PsaImporter(object): import_bone.orig_quat = armature_bone.matrix_local.to_quaternion() import_bone.post_quat = import_bone.orig_quat.conjugated() - io_time = datetime.timedelta() - math_time = datetime.timedelta() - keyframe_time = datetime.timedelta() - # Create and populate the data for new sequences. for sequence in sequences: # F-curve data buffer for all bones. This is used later on to avoid adding redundant keyframes. @@ -120,10 +116,7 @@ class PsaImporter(object): # Read the sequence keys from the PSA file. sequence_name = sequence.name.decode('windows-1252') - - now = datetime.datetime.now() sequence_keys = psa_reader.read_sequence_keys(sequence_name) - io_time += datetime.datetime.now() - now # Add keyframes for each frame of the sequence. for frame_index in reversed(range(sequence.frame_count)): @@ -134,7 +127,6 @@ class PsaImporter(object): key_index += 1 continue - now = datetime.datetime.now() # Convert world-space transforms to local-space transforms. key_rotation = Quaternion(tuple(sequence_keys[key_index].rotation)) q = import_bone.post_quat.copy() @@ -149,9 +141,7 @@ class PsaImporter(object): key_location = Vector(tuple(sequence_keys[key_index].location)) loc = key_location - import_bone.orig_loc loc.rotate(import_bone.post_quat.conjugated()) - math_time += datetime.datetime.now() - now - now = datetime.datetime.now() # Add keyframe data for each of the associated f-curves. bone_fcurve_data = quat.w, quat.x, quat.y, quat.z, loc.x, loc.y, loc.z @@ -171,16 +161,14 @@ class PsaImporter(object): next_frame_bones_fcurve_data[bone_index] = bone_fcurve_data - keyframe_time += datetime.datetime.now() - now key_index += 1 - # TODO: eliminate last keyframe if there are only two keyframes (beginning + end and the values are identical) - # in this way, we will effectively have cleaned the keyframes inline. - pass - - print(f'io_time: {io_time}') - print(f'math_time: {math_time}') - print(f'keyframe_time: {keyframe_time}') + # Eliminate redundant final keyframe if the f-curve value is identical to the previous keyframe. + for import_bone in filter(lambda x: x is not None, import_bones): + for fcurve in filter(lambda x: len(x.keyframe_points) > 1, import_bone.fcurves): + second_to_last_keyframe, last_keyframe = fcurve.keyframe_points[-2:] + if second_to_last_keyframe.co[1] == last_keyframe.co[1]: + fcurve.keyframe_points.remove(last_keyframe) class PsaImportActionListItem(PropertyGroup): From 41e14d5e19ccc994c3c549dc17ab50cf7154ff26 Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Wed, 19 Jan 2022 02:55:10 -0800 Subject: [PATCH 12/19] Fixed keyframe "bleeding" on PSA import --- io_export_psk_psa/psa/data.py | 10 +++ io_export_psk_psa/psa/importer.py | 112 +++++++++++++++++------------- io_export_psk_psa/psa/reader.py | 15 +++- 3 files changed, 89 insertions(+), 48 deletions(-) diff --git a/io_export_psk_psa/psa/data.py b/io_export_psk_psa/psa/data.py index 1ebef63..6f4e484 100644 --- a/io_export_psk_psa/psa/data.py +++ b/io_export_psk_psa/psa/data.py @@ -44,6 +44,16 @@ class Psa(object): ('time', c_float) ] + @property + def data(self): + yield self.rotation.w + yield self.rotation.x + yield self.rotation.y + yield self.rotation.z + yield self.location.x + yield self.location.y + yield self.location.z + def __repr__(self) -> str: return repr((self.location, self.rotation, self.time)) diff --git a/io_export_psk_psa/psa/importer.py b/io_export_psk_psa/psa/importer.py index 37a425c..b471e02 100644 --- a/io_export_psk_psa/psa/importer.py +++ b/io_export_psk_psa/psa/importer.py @@ -33,6 +33,23 @@ class PsaImporter(object): self.post_quat: Quaternion = Quaternion() self.fcurves = [] + def calculate_fcurve_data(import_bone: ImportBone, key_data: []): + # Convert world-space transforms to local-space transforms. + key_rotation = Quaternion(key_data[0:4]) + key_location = Vector(key_data[4:]) + q = import_bone.post_quat.copy() + q.rotate(import_bone.orig_quat) + quat = q + q = import_bone.post_quat.copy() + if import_bone.parent is None: + q.rotate(key_rotation.conjugated()) + else: + q.rotate(key_rotation) + quat.rotate(q.conjugated()) + loc = key_location - import_bone.orig_loc + loc.rotate(import_bone.post_quat.conjugated()) + return quat.w, quat.x, quat.y, quat.z, loc.x, loc.y, loc.z + # Create an index mapping from bones in the PSA to bones in the target armature. psa_to_armature_bone_indices = {} armature_bone_names = [x.name for x in armature_data.bones] @@ -90,6 +107,13 @@ class PsaImporter(object): import_bone.orig_quat = armature_bone.matrix_local.to_quaternion() import_bone.post_quat = import_bone.orig_quat.conjugated() + io_time = datetime.timedelta() + math_time = datetime.timedelta() + keyframe_time = datetime.timedelta() + total_time = datetime.timedelta() + + total_datetime_start = datetime.datetime.now() + # Create and populate the data for new sequences. for sequence in sequences: # F-curve data buffer for all bones. This is used later on to avoid adding redundant keyframes. @@ -116,59 +140,54 @@ class PsaImporter(object): # Read the sequence keys from the PSA file. sequence_name = sequence.name.decode('windows-1252') - sequence_keys = psa_reader.read_sequence_keys(sequence_name) - # Add keyframes for each frame of the sequence. - for frame_index in reversed(range(sequence.frame_count)): - key_index = frame_index * len(import_bones) + # Read the sequence data matrix from the PSA. + start_datetime = datetime.datetime.now() + sequence_data_matrix = psa_reader.read_sequence_data_matrix(sequence_name) + keyframe_write_matrix = np.ones(sequence_data_matrix.shape, dtype=np.int8) + io_time += datetime.datetime.now() - start_datetime + + # The first step is to determine the frames at which each bone will write out a keyframe. + threshold = 0.001 + for bone_index, import_bone in enumerate(import_bones): + if import_bone is None: + continue + for fcurve_index, fcurve in enumerate(import_bone.fcurves): + # Get all the keyframe data for the bone's f-curve data from the sequence data matrix. + fcurve_frame_data = sequence_data_matrix[:, bone_index, fcurve_index] + last_written_datum = 0 + for frame_index, datum in enumerate(fcurve_frame_data): + # If the f-curve data is not different enough to the last written frame, un-mark this data for writing. + if frame_index > 0 and abs(datum - last_written_datum) < threshold: + keyframe_write_matrix[frame_index, bone_index, fcurve_index] = 0 + else: + last_written_datum = fcurve_frame_data[frame_index] + + # Write the keyframes out! + for frame_index in range(sequence.frame_count): for bone_index, import_bone in enumerate(import_bones): if import_bone is None: - # bone does not exist in the armature, skip it - key_index += 1 continue - - # Convert world-space transforms to local-space transforms. - key_rotation = Quaternion(tuple(sequence_keys[key_index].rotation)) - q = import_bone.post_quat.copy() - q.rotate(import_bone.orig_quat) - quat = q - q = import_bone.post_quat.copy() - if import_bone.parent is None: - q.rotate(key_rotation.conjugated()) - else: - q.rotate(key_rotation) - quat.rotate(q.conjugated()) - key_location = Vector(tuple(sequence_keys[key_index].location)) - loc = key_location - import_bone.orig_loc - loc.rotate(import_bone.post_quat.conjugated()) - - # Add keyframe data for each of the associated f-curves. - bone_fcurve_data = quat.w, quat.x, quat.y, quat.z, loc.x, loc.y, loc.z - - if frame_index == 0: - # Always add a keyframe on the first frame. - for fcurve, datum in zip(import_bone.fcurves, bone_fcurve_data): - fcurve.keyframe_points.insert(frame_index, datum, options={'FAST'}) - else: - # For each f-curve, check that the next frame has data that differs from the current frame. - # If so, add a keyframe for the current frame. - # Note that we are iterating the frames in reverse order. - threshold = 0.001 - for fcurve, datum, old_datum in zip(import_bone.fcurves, bone_fcurve_data, next_frame_bones_fcurve_data[bone_index]): - # Only - if abs(datum - old_datum) > threshold: + bone_has_writeable_keyframes = any(keyframe_write_matrix[frame_index, bone_index]) + if bone_has_writeable_keyframes: + # This bone has writeable keyframes for this frame. + key_data = sequence_data_matrix[frame_index, bone_index] + # Calculate the local-space key data for the bone. + start_datetime = datetime.datetime.now() + fcurve_data = calculate_fcurve_data(import_bone, key_data) + math_time += datetime.datetime.now() - start_datetime + for fcurve, should_write, datum in zip(import_bone.fcurves, keyframe_write_matrix[frame_index, bone_index], fcurve_data): + if should_write: + start_datetime = datetime.datetime.now() fcurve.keyframe_points.insert(frame_index, datum, options={'FAST'}) + keyframe_time += datetime.datetime.now() - start_datetime - next_frame_bones_fcurve_data[bone_index] = bone_fcurve_data + total_time = datetime.datetime.now() - total_datetime_start - key_index += 1 - - # Eliminate redundant final keyframe if the f-curve value is identical to the previous keyframe. - for import_bone in filter(lambda x: x is not None, import_bones): - for fcurve in filter(lambda x: len(x.keyframe_points) > 1, import_bone.fcurves): - second_to_last_keyframe, last_keyframe = fcurve.keyframe_points[-2:] - if second_to_last_keyframe.co[1] == last_keyframe.co[1]: - fcurve.keyframe_points.remove(last_keyframe) + print(f'io_time: {io_time}') + print(f'math_time: {math_time}') + print(f'keyframe_time: {keyframe_time}') + print(f'total_time: {total_time}') class PsaImportActionListItem(PropertyGroup): @@ -186,7 +205,6 @@ def on_psa_file_path_updated(property, context): try: # Read the file and populate the action list. p = os.path.abspath(context.scene.psa_import.psa_file_path) - print(p) psa_reader = PsaReader(p) for sequence in psa_reader.sequences.values(): item = context.scene.psa_import.action_list.add() diff --git a/io_export_psk_psa/psa/reader.py b/io_export_psk_psa/psa/reader.py index ee99e59..b9246cd 100644 --- a/io_export_psk_psa/psa/reader.py +++ b/io_export_psk_psa/psa/reader.py @@ -1,5 +1,6 @@ from .data import * import ctypes +import numpy as np class PsaReader(object): @@ -30,7 +31,19 @@ class PsaReader(object): data.append(data_class.from_buffer_copy(buffer, offset)) offset += section.data_size - def read_sequence_keys(self, sequence_name) -> List[Psa.Key]: + def read_sequence_data_matrix(self, sequence_name: str): + sequence = self.psa.sequences[sequence_name] + keys = self.read_sequence_keys(sequence_name) + bone_count = len(self.bones) + matrix_size = sequence.frame_count, bone_count, 7 + matrix = np.zeros(matrix_size) + keys_iter = iter(keys) + for frame_index in range(sequence.frame_count): + for bone_index in range(bone_count): + matrix[frame_index, bone_index, :] = list(next(keys_iter).data) + return matrix + + def read_sequence_keys(self, sequence_name: str) -> List[Psa.Key]: """ Reads and returns the key data for a sequence. :param sequence_name: The name of the sequence. From abef2a7f4548c805c4c8bbd804801ced4bbe0dee Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Sat, 22 Jan 2022 18:11:41 -0800 Subject: [PATCH 13/19] Bone group filtering is now working for both PSK and PSA exports. --- io_export_psk_psa/__init__.py | 20 ++++-- io_export_psk_psa/helpers.py | 60 +++++++++++++++++ io_export_psk_psa/psa/builder.py | 41 +++++------- io_export_psk_psa/psa/exporter.py | 107 +++++++++++++++--------------- io_export_psk_psa/psa/importer.py | 81 +++++++++++++++------- io_export_psk_psa/psk/builder.py | 72 ++++++++++++++++---- io_export_psk_psa/psk/exporter.py | 71 ++++++++++++++++++-- io_export_psk_psa/types.py | 25 +++++++ 8 files changed, 353 insertions(+), 124 deletions(-) create mode 100644 io_export_psk_psa/helpers.py create mode 100644 io_export_psk_psa/types.py diff --git a/io_export_psk_psa/__init__.py b/io_export_psk_psa/__init__.py index 10454f1..d29d0e4 100644 --- a/io_export_psk_psa/__init__.py +++ b/io_export_psk_psa/__init__.py @@ -13,6 +13,9 @@ bl_info = { if 'bpy' in locals(): import importlib + importlib.reload(psx_data) + importlib.reload(psx_helpers) + importlib.reload(psx_types) importlib.reload(psk_data) importlib.reload(psk_builder) importlib.reload(psk_exporter) @@ -25,6 +28,9 @@ if 'bpy' in locals(): importlib.reload(psa_importer) else: # if i remove this line, it can be enabled just fine + from . import data as psx_data + from . import helpers as psx_helpers + from . import types as psx_types from .psk import data as psk_data from .psk import builder as psk_builder from .psk import exporter as psk_exporter @@ -40,15 +46,19 @@ import bpy from bpy.props import PointerProperty -classes = [ - psk_exporter.PskExportOperator, +# TODO: have the individual files emit a __classes__ field or something we can update it locally instead of explicitly declaring it here. +classes = [] +classes.extend(psx_types.__classes__) +classes.extend(psk_exporter.__classes__) +classes.extend([ psk_importer.PskImportOperator, psa_importer.PsaImportOperator, psa_importer.PsaImportFileSelectOperator, psa_exporter.PSA_UL_ExportActionList, - psa_exporter.PSA_UL_ExportBoneGroupList, + # psa_exporter.PSA_UL_ExportBoneGroupList, psa_importer.PSA_UL_ImportActionList, psa_importer.PsaImportActionListItem, + psa_importer.PsaImportPsaBoneItem, psa_importer.PsaImportSelectAll, psa_importer.PsaImportDeselectAll, psa_importer.PSA_PT_ImportPanel, @@ -57,9 +67,8 @@ classes = [ psa_exporter.PsaExportSelectAll, psa_exporter.PsaExportDeselectAll, psa_exporter.PsaExportActionListItem, - psa_exporter.PsaExportBoneGroupListItem, psa_exporter.PsaExportPropertyGroup, -] +]) def psk_export_menu_func(self, context): @@ -87,6 +96,7 @@ def register(): bpy.types.TOPBAR_MT_file_import.append(psa_import_menu_func) bpy.types.Scene.psa_import = PointerProperty(type=psa_importer.PsaImportPropertyGroup) bpy.types.Scene.psa_export = PointerProperty(type=psa_exporter.PsaExportPropertyGroup) + bpy.types.Scene.psk_export = PointerProperty(type=psk_exporter.PskExportPropertyGroup) def unregister(): diff --git a/io_export_psk_psa/helpers.py b/io_export_psk_psa/helpers.py new file mode 100644 index 0000000..f8bcb4c --- /dev/null +++ b/io_export_psk_psa/helpers.py @@ -0,0 +1,60 @@ +from typing import List + + +def populate_bone_groups_list(armature_object, bone_group_list): + bone_group_list.clear() + + item = bone_group_list.add() + item.name = '(unassigned)' + item.index = -1 + item.is_selected = True + + for bone_group_index, bone_group in enumerate(armature_object.pose.bone_groups): + item = bone_group_list.add() + item.name = bone_group.name + item.index = bone_group_index + item.is_selected = True + + +def add_bone_groups_to_layout(layout): + pass + + +def get_export_bone_indices_for_bone_groups(armature_object, bone_group_indices: List[int]) -> List[int]: + """ + Returns a sorted list of bone indices that should be exported for the given bone groups. + + Note that the ancestors of bones within the bone groups will also be present in the returned list. + + :param armature_object: Blender object with type 'ARMATURE' + :param bone_group_indices: List of bone group indices to be exported. + :return: A sorted list of bone indices that should be exported. + """ + if armature_object is None or armature_object.type != 'ARMATURE': + raise ValueError('An armature object must be supplied') + + bones = armature_object.data.bones + pose_bones = armature_object.pose.bones + bone_names = [x.name for x in bones] + + # Get a list of the bone indices that are explicitly part of the bone groups we are including. + bone_index_stack = [] + is_exporting_none_bone_groups = -1 in bone_group_indices + for bone_index, pose_bone in enumerate(pose_bones): + if (pose_bone.bone_group is None and is_exporting_none_bone_groups) or \ + (pose_bone.bone_group is not None and pose_bone.bone_group_index in bone_group_indices): + bone_index_stack.append(bone_index) + + # For each bone that is explicitly being added, recursively walk up the hierarchy and ensure that all of + # those ancestor bone indices are also in the list. + bone_indices = set() + while len(bone_index_stack) > 0: + bone_index = bone_index_stack.pop() + bone = bones[bone_index] + if bone.parent is not None: + parent_bone_index = bone_names.index(bone.parent.name) + if parent_bone_index not in bone_indices: + bone_index_stack.append(parent_bone_index) + bone_indices.add(bone_index) + + return list(sorted(list(bone_indices))) diff --git a/io_export_psk_psa/psa/builder.py b/io_export_psk_psa/psa/builder.py index 0ae9244..2f11438 100644 --- a/io_export_psk_psa/psa/builder.py +++ b/io_export_psk_psa/psa/builder.py @@ -1,10 +1,11 @@ from .data import * +from ..helpers import * class PsaBuilderOptions(object): def __init__(self): self.actions = [] - self.bone_filter_mode = 'NONE' + self.bone_filter_mode = 'ALL' self.bone_group_indices = [] @@ -34,39 +35,31 @@ class PsaBuilder(object): # armature bones. bone_names = [x.name for x in bones] pose_bones = [(bone_names.index(bone.name), bone) for bone in armature.pose.bones] + del bone_names pose_bones.sort(key=lambda x: x[0]) pose_bones = [x[1] for x in pose_bones] bone_indices = list(range(len(bones))) + # If bone groups are specified, get only the bones that are in that specified bone groups and their ancestors. if options.bone_filter_mode == 'BONE_GROUPS': - # Get a list of the bone indices that are explicitly part of the bone groups we are including. - bone_index_stack = [] - for bone_index, pose_bone in enumerate(pose_bones): - if pose_bone.bone_group_index in options.bone_group_indices: - bone_index_stack.append(bone_index) + bone_indices = get_export_bone_indices_for_bone_groups(armature, options.bone_group_indices) - # For each bone that is explicitly being added, recursively walk up the hierarchy and ensure that all of - # those bone indices are also in the list. - bone_indices = set() - while len(bone_index_stack) > 0: - bone_index = bone_index_stack.pop() - bone = bones[bone_index] - if bone.parent is not None: - parent_bone_index = bone_names.index(bone.parent.name) - if parent_bone_index not in bone_indices: - bone_index_stack.append(parent_bone_index) - bone_indices.add(bone_index) - - del bone_names - - # Sort out list of bone indices to be exported. - bone_indices = sorted(list(bone_indices)) - - # The bone lists now contains only the bones that are going to be exported. + # Make the bone lists contain only the bones that are going to be exported. bones = [bones[bone_index] for bone_index in bone_indices] pose_bones = [pose_bones[bone_index] for bone_index in bone_indices] + if len(bones) == 0: + # No bones are going to be exported. + raise RuntimeError('No bones available for export') + + # Ensure that the exported hierarchy has a single root bone. + root_bones = [x for x in bones if x.parent is None] + if len(root_bones) > 1: + root_bone_names = [x.name for x in bones] + raise RuntimeError('Exported bone hierarchy must have a single root bone.' + f'The bone hierarchy marked for export has {len(root_bones)} root bones: {root_bone_names}') + for pose_bone in bones: psa_bone = Psa.Bone() psa_bone.name = bytes(pose_bone.name, encoding='utf-8') diff --git a/io_export_psk_psa/psa/exporter.py b/io_export_psk_psa/psa/exporter.py index 587a586..643a6e6 100644 --- a/io_export_psk_psa/psa/exporter.py +++ b/io_export_psk_psa/psa/exporter.py @@ -5,6 +5,8 @@ from bpy_extras.io_utils import ExportHelper from typing import Type from .builder import PsaBuilder, PsaBuilderOptions from .data import * +from ..types import BoneGroupListItem +from ..helpers import * import re @@ -43,30 +45,29 @@ class PsaExportActionListItem(PropertyGroup): return self.action.name -class PsaExportBoneGroupListItem(PropertyGroup): - name: StringProperty() - index: IntProperty() - is_selected: BoolProperty(default=False) - - @property - def name(self): - return self.bone_group.name - - class PsaExportPropertyGroup(PropertyGroup): action_list: CollectionProperty(type=PsaExportActionListItem) action_list_index: IntProperty(default=0) bone_filter_mode: EnumProperty( name='Bone Filter', - items={ - ('NONE', 'None', 'All bones will be exported.'), - ('BONE_GROUPS', 'Bone Groups', 'Only bones belonging to the selected bone groups will be exported.'), - } + description='', + items=( + ('ALL', 'All', 'All bones will be exported.'), + ('BONE_GROUPS', 'Bone Groups', 'Only bones belonging to the selected bone groups and their ancestors will be exported.') + ) ) - bone_group_list: CollectionProperty(type=PsaExportBoneGroupListItem) + bone_group_list: CollectionProperty(type=BoneGroupListItem) bone_group_list_index: IntProperty(default=0) +def is_bone_filter_mode_item_available(context, identifier): + if identifier == "BONE_GROUPS": + obj = context.active_object + if not obj.pose or not obj.pose.bone_groups: + return False + return True + + class PsaExportOperator(Operator, ExportHelper): bl_idname = 'export.psa' bl_label = 'Export' @@ -84,29 +85,34 @@ class PsaExportOperator(Operator, ExportHelper): def draw(self, context): layout = self.layout - scene = context.scene + property_group = context.scene.psa_export + # ACTIONS box = layout.box() box.label(text='Actions', icon='ACTION') - row = box.row() - row.template_list('PSA_UL_ExportActionList', 'asd', scene.psa_export, 'action_list', scene.psa_export, 'action_list_index', rows=10) - - row = box.row() - row.operator('psa_export.actions_select_all', text='Select All') - row.operator('psa_export.actions_deselect_all', text='Deselect All') + row.template_list('PSA_UL_ExportActionList', 'asd', property_group, 'action_list', property_group, 'action_list_index', rows=10) + row = box.row(align=True) + row.label(text='Select') + row.operator('psa_export.actions_select_all', text='All') + row.operator('psa_export.actions_deselect_all', text='None') + # BONES box = layout.box() - box.label(text='Bone Filter', icon='FILTER') + box.label(text='Bones', icon='BONE_DATA') + bone_filter_mode_items = property_group.bl_rna.properties['bone_filter_mode'].enum_items_static + row = box.row(align=True) + for item in bone_filter_mode_items: + identifier = item.identifier + item_layout = row.row(align=True) + item_layout.prop_enum(property_group, 'bone_filter_mode', item.identifier) + item_layout.enabled = is_bone_filter_mode_item_available(context, identifier) - row = box.row() - row.alignment = 'EXPAND' - row.prop(scene.psa_export, 'bone_filter_mode', expand=True, text='Bone Filter') - - if scene.psa_export.bone_filter_mode == 'BONE_GROUPS': + if property_group.bone_filter_mode == 'BONE_GROUPS': + box = layout.box() row = box.row() - rows = max(3, min(len(scene.psa_export.bone_group_list), 10)) - row.template_list('PSA_UL_ExportBoneGroupList', 'asd', scene.psa_export, 'bone_group_list', scene.psa_export, 'bone_group_list_index', rows=rows) + rows = max(3, min(len(property_group.bone_group_list), 10)) + row.template_list('PSX_UL_BoneGroupList', '', property_group, 'bone_group_list', property_group, 'bone_group_list_index', rows=rows) def is_action_for_armature(self, action): if len(action.fcurves) == 0: @@ -122,6 +128,8 @@ class PsaExportOperator(Operator, ExportHelper): return False def invoke(self, context, event): + property_group = context.scene.psa_export + if context.view_layer.objects.active is None: self.report({'ERROR_INVALID_CONTEXT'}, 'An armature must be selected') return {'CANCELLED'} @@ -133,33 +141,29 @@ class PsaExportOperator(Operator, ExportHelper): self.armature = context.view_layer.objects.active # Populate actions list. - context.scene.psa_export.action_list.clear() + property_group.action_list.clear() for action in bpy.data.actions: - item = context.scene.psa_export.action_list.add() + item = property_group.action_list.add() item.action = action item.action_name = action.name if self.is_action_for_armature(action): item.is_selected = True - if len(context.scene.psa_export.action_list) == 0: + if len(property_group.action_list) == 0: # If there are no actions at all, we have nothing to export, so just cancel the operation. self.report({'ERROR_INVALID_CONTEXT'}, 'There are no actions to export.') return {'CANCELLED'} # Populate bone groups list. - context.scene.psa_export.bone_group_list.clear() - for bone_group_index, bone_group in enumerate(self.armature.pose.bone_groups): - item = context.scene.psa_export.bone_group_list.add() - item.name = bone_group.name - item.index = bone_group_index - item.is_selected = False + populate_bone_groups_list(self.armature, property_group.bone_group_list) context.window_manager.fileselect_add(self) return {'RUNNING_MODAL'} def execute(self, context): - actions = [x.action for x in context.scene.psa_export.action_list if x.is_selected] + property_group = context.scene.psa_export + actions = [x.action for x in property_group.action_list if x.is_selected] if len(actions) == 0: self.report({'ERROR_INVALID_CONTEXT'}, 'No actions were selected for export.') @@ -167,8 +171,8 @@ class PsaExportOperator(Operator, ExportHelper): options = PsaBuilderOptions() options.actions = actions - options.bone_filter_mode = context.scene.psa_export.bone_filter_mode - options.bone_group_indices = [x.index for x in context.scene.psa_export.bone_group_list if x.is_selected] + options.bone_filter_mode = property_group.bone_filter_mode + options.bone_group_indices = [x.index for x in property_group.bone_group_list if x.is_selected] builder = PsaBuilder() psa = builder.build(context, options) exporter = PsaExporter(psa) @@ -176,13 +180,6 @@ class PsaExportOperator(Operator, ExportHelper): return {'FINISHED'} -class PSA_UL_ExportBoneGroupList(UIList): - def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): - layout.alignment = 'LEFT' - layout.prop(item, 'is_selected', icon_only=True) - layout.label(text=item.name, icon='GROUP_BONE') - - class PSA_UL_ExportActionList(UIList): def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): layout.alignment = 'LEFT' @@ -210,12 +207,14 @@ class PsaExportSelectAll(bpy.types.Operator): @classmethod def poll(cls, context): - action_list = context.scene.psa_export.action_list + property_group = context.scene.psa_export + action_list = property_group.action_list has_unselected_actions = any(map(lambda action: not action.is_selected, action_list)) return len(action_list) > 0 and has_unselected_actions def execute(self, context): - for action in context.scene.psa_export.action_list: + property_group = context.scene.psa_export + for action in property_group.action_list: action.is_selected = True return {'FINISHED'} @@ -226,11 +225,13 @@ class PsaExportDeselectAll(bpy.types.Operator): @classmethod def poll(cls, context): - action_list = context.scene.psa_export.action_list + property_group = context.scene.psa_export + action_list = property_group.action_list has_selected_actions = any(map(lambda action: action.is_selected, action_list)) return len(action_list) > 0 and has_selected_actions def execute(self, context): - for action in context.scene.psa_export.action_list: + property_group = context.scene.psa_export + for action in property_group.action_list: action.is_selected = False return {'FINISHED'} diff --git a/io_export_psk_psa/psa/importer.py b/io_export_psk_psa/psa/importer.py index b471e02..996e96e 100644 --- a/io_export_psk_psa/psa/importer.py +++ b/io_export_psk_psa/psa/importer.py @@ -17,9 +17,9 @@ class PsaImporter(object): pass def import_psa(self, psa_reader: PsaReader, sequence_names: List[AnyStr], context): - properties = context.scene.psa_import + property_group = context.scene.psa_import sequences = map(lambda x: psa_reader.sequences[x], sequence_names) - armature_object = properties.armature_object + armature_object = property_group.armature_object armature_data = armature_object.data class ImportBone(object): @@ -190,6 +190,14 @@ class PsaImporter(object): print(f'total_time: {total_time}') +class PsaImportPsaBoneItem(PropertyGroup): + bone_name: StringProperty() + + @property + def name(self): + return self.bone_name + + class PsaImportActionListItem(PropertyGroup): action_name: StringProperty() frame_count: IntProperty() @@ -201,16 +209,22 @@ class PsaImportActionListItem(PropertyGroup): def on_psa_file_path_updated(property, context): - context.scene.psa_import.action_list.clear() + property_group = context.scene.psa_import + property_group.action_list.clear() + property_group.psa_bones.clear() try: # Read the file and populate the action list. - p = os.path.abspath(context.scene.psa_import.psa_file_path) + p = os.path.abspath(property_group.psa_file_path) psa_reader = PsaReader(p) for sequence in psa_reader.sequences.values(): - item = context.scene.psa_import.action_list.add() + item = property_group.action_list.add() item.action_name = sequence.name.decode('windows-1252') item.frame_count = sequence.frame_count item.is_selected = True + + for psa_bone in psa_reader.bones: + item = property_group.psa_bones.add() + item.bone_name = psa_bone.name except IOError as e: print('ERROR READING FILE') print(e) @@ -218,9 +232,19 @@ def on_psa_file_path_updated(property, context): pass +def on_armature_object_updated(property, context): + # TODO: ensure that there are matching bones between the two rigs. + property_group = context.scene.psa_import + armature_object = property_group.armature_object + if armature_object is not None: + armature_bone_names = set(map(lambda bone: bone.name, armature_object.data.bones)) + psa_bone_names = set(map(lambda psa_bone: psa_bone.name, property_group.psa_bones)) + + class PsaImportPropertyGroup(bpy.types.PropertyGroup): psa_file_path: StringProperty(default='', subtype='FILE_PATH', update=on_psa_file_path_updated) - armature_object: PointerProperty(name='Armature', type=bpy.types.Object) + psa_bones: CollectionProperty(type=PsaImportPsaBoneItem) + armature_object: PointerProperty(name='Object', type=bpy.types.Object, update=on_armature_object_updated) action_list: CollectionProperty(type=PsaImportActionListItem) action_list_index: IntProperty(name='', default=0) action_filter_name: StringProperty(default='') @@ -265,12 +289,14 @@ class PsaImportSelectAll(bpy.types.Operator): @classmethod def poll(cls, context): - action_list = context.scene.psa_import.action_list + property_group = context.scene.psa_import + action_list = property_group.action_list has_unselected_actions = any(map(lambda action: not action.is_selected, action_list)) return len(action_list) > 0 and has_unselected_actions def execute(self, context): - for action in context.scene.psa_import.action_list: + property_group = context.scene.psa_import + for action in property_group.action_list: action.is_selected = True return {'FINISHED'} @@ -281,35 +307,41 @@ class PsaImportDeselectAll(bpy.types.Operator): @classmethod def poll(cls, context): - action_list = context.scene.psa_import.action_list + property_group = context.scene.psa_import + action_list = property_group.action_list has_selected_actions = any(map(lambda action: action.is_selected, action_list)) return len(action_list) > 0 and has_selected_actions def execute(self, context): - for action in context.scene.psa_import.action_list: + property_group = context.scene.psa_import + for action in property_group.action_list: action.is_selected = False return {'FINISHED'} class PSA_PT_ImportPanel(Panel): - bl_space_type = 'VIEW_3D' + bl_space_type = 'NLA_EDITOR' bl_region_type = 'UI' bl_label = 'PSA Import' - bl_context = 'objectmode' + bl_context = 'object' bl_category = 'PSA Import' + @classmethod + def poll(cls, context): + return context.view_layer.objects.active is not None + def draw(self, context): layout = self.layout - scene = context.scene + property_group = context.scene.psa_import row = layout.row() - row.prop(scene.psa_import, 'psa_file_path', text='PSA File') + row.prop(property_group, 'psa_file_path', text='PSA File') row = layout.row() - row.prop_search(scene.psa_import, 'armature_object', bpy.data, 'objects') + row.prop_search(property_group, 'armature_object', bpy.data, 'objects') box = layout.box() - box.label(text=f'Actions ({len(scene.psa_import.action_list)})', icon='ACTION') + box.label(text=f'Actions ({len(property_group.action_list)})', icon='ACTION') row = box.row() - rows = max(3, min(len(scene.psa_import.action_list), 10)) - row.template_list('PSA_UL_ImportActionList', 'asd', scene.psa_import, 'action_list', scene.psa_import, 'action_list_index', rows=rows) + rows = max(3, min(len(property_group.action_list), 10)) + row.template_list('PSA_UL_ImportActionList', '', property_group, 'action_list', property_group, 'action_list_index', rows=rows) row = box.row(align=True) row.label(text='Select') row.operator('psa_import.actions_select_all', text='All') @@ -323,14 +355,16 @@ class PsaImportOperator(Operator): @classmethod def poll(cls, context): - action_list = context.scene.psa_import.action_list + property_group = context.scene.psa_import + action_list = property_group.action_list has_selected_actions = any(map(lambda action: action.is_selected, action_list)) - armature_object = context.scene.psa_import.armature_object + armature_object = property_group.armature_object return has_selected_actions and armature_object is not None def execute(self, context): - psa_reader = PsaReader(context.scene.psa_import.psa_file_path) - sequence_names = [x.action_name for x in context.scene.psa_import.action_list if x.is_selected] + property_group = context.scene.psa_import + psa_reader = PsaReader(property_group.psa_file_path) + sequence_names = [x.action_name for x in property_group.action_list if x.is_selected] PsaImporter().import_psa(psa_reader, sequence_names, context) return {'FINISHED'} @@ -351,6 +385,7 @@ class PsaImportFileSelectOperator(Operator, ImportHelper): return {'RUNNING_MODAL'} def execute(self, context): - context.scene.psa_import.psa_file_path = self.filepath + property_group = context.scene.psa_import + property_group.psa_file_path = self.filepath # Load the sequence names from the selected file return {'FINISHED'} diff --git a/io_export_psk_psa/psk/builder.py b/io_export_psk_psa/psk/builder.py index c5d92a0..f27bd12 100644 --- a/io_export_psk_psa/psk/builder.py +++ b/io_export_psk_psa/psk/builder.py @@ -2,8 +2,8 @@ import bpy import bmesh from collections import OrderedDict from .data import * +from ..helpers import * -# https://github.com/bwrsandman/blender-addons/blob/master/io_export_unreal_psk_psa.py class PskInputObjects(object): def __init__(self): @@ -11,6 +11,12 @@ class PskInputObjects(object): self.armature_object = None +class PskBuilderOptions(object): + def __init__(self): + self.bone_filter_mode = 'ALL' + self.bone_group_indices = [] + + class PskBuilder(object): def __init__(self): pass @@ -51,13 +57,16 @@ class PskBuilder(object): return input_objects - def build(self, context) -> Psk: + def build(self, context, options: PskBuilderOptions) -> Psk: input_objects = PskBuilder.get_input_objects(context) + armature_object = input_objects.armature_object + psk = Psk() + bones = [] materials = OrderedDict() - if input_objects.armature_object is None: + if armature_object is None: # Static mesh (no armature) psk_bone = Psk.Bone() psk_bone.name = bytes('static', encoding='utf-8') @@ -68,15 +77,30 @@ class PskBuilder(object): psk_bone.rotation = Quaternion(0, 0, 0, 1) psk.bones.append(psk_bone) else: - bones = list(input_objects.armature_object.data.bones) + bones = list(armature_object.data.bones) + + # If bone groups are specified, get only the bones that are in the specified bone groups and their ancestors. + if len(options.bone_group_indices) > 0: + bone_indices = get_export_bone_indices_for_bone_groups(armature_object, options.bone_group_indices) + bones = [bones[bone_index] for bone_index in bone_indices] + + # Ensure that the exported hierarchy has a single root bone. + root_bones = [x for x in bones if x.parent is None] + if len(root_bones) > 1: + root_bone_names = [x.name for x in bones] + raise RuntimeError('Exported bone hierarchy must have a single root bone.' + f'The bone hierarchy marked for export has {len(root_bones)} root bones: {root_bone_names}') + for bone in bones: psk_bone = Psk.Bone() psk_bone.name = bytes(bone.name, encoding='utf-8') psk_bone.flags = 0 - psk_bone.children_count = len(bone.children) + psk_bone.children_count = 0 try: - psk_bone.parent_index = bones.index(bone.parent) + parent_index = bones.index(bone.parent) + psk_bone.parent_index = parent_index + psk.bones[parent_index].children_count += 1 except ValueError: psk_bone.parent_index = 0 @@ -90,8 +114,8 @@ class PskBuilder(object): parent_tail = quat_parent @ bone.parent.tail location = (parent_tail - parent_head) + bone.head else: - location = input_objects.armature_object.matrix_local @ bone.head - rot_matrix = bone.matrix @ input_objects.armature_object.matrix_local.to_3x3() + location = armature_object.matrix_local @ bone.head + rot_matrix = bone.matrix @ armature_object.matrix_local.to_3x3() rotation = rot_matrix.to_quaternion() psk_bone.location.x = location.x @@ -177,14 +201,34 @@ class PskBuilder(object): psk.faces.append(face) # WEIGHTS - # TODO: bone ~> vg might not be 1:1, provide a nice error message if this is the case - if input_objects.armature_object is not None: - armature = input_objects.armature_object.data - bone_names = [x.name for x in armature.bones] + if armature_object is not None: + # Because the vertex groups may contain entries for which there is no matching bone in the armature, + # we must filter them out and not export any weights for these vertex groups. + bone_names = [x.name for x in bones] vertex_group_names = [x.name for x in object.vertex_groups] - bone_indices = [bone_names.index(name) for name in vertex_group_names] + vertex_group_bone_indices = dict() + for vertex_group_index, vertex_group_name in enumerate(vertex_group_names): + try: + vertex_group_bone_indices[vertex_group_index] = bone_names.index(vertex_group_name) + except ValueError: + # The vertex group does not have a matching bone in the list of bones to be exported. + # Check to see if there is an associated bone for this vertex group that exists in the armature. + # If there is, we can traverse the ancestors of that bone to find an alternate bone to use for + # weighting the vertices belonging to this vertex group. + if vertex_group_name in armature_object.data.bones: + bone = armature_object.data.bones[vertex_group_name] + while bone is not None: + try: + bone_index = bone_names.index(bone.name) + vertex_group_bone_indices[vertex_group_index] = bone_index + break + except ValueError: + bone = bone.parent for vertex_group_index, vertex_group in enumerate(object.vertex_groups): - bone_index = bone_indices[vertex_group_index] + if vertex_group_index not in vertex_group_bone_indices: + continue + bone_index = vertex_group_bone_indices[vertex_group_index] + # TODO: exclude vertex group if it doesn't match to a bone we are exporting for vertex_index in range(len(object.data.vertices)): try: weight = vertex_group.weight(vertex_index) diff --git a/io_export_psk_psa/psk/exporter.py b/io_export_psk_psa/psk/exporter.py index bc90446..4e9b930 100644 --- a/io_export_psk_psa/psk/exporter.py +++ b/io_export_psk_psa/psk/exporter.py @@ -1,9 +1,11 @@ from .data import * -from .builder import PskBuilder +from ..types import BoneGroupListItem +from ..helpers import populate_bone_group_list +from .builder import PskBuilder, PskBuilderOptions from typing import Type -from bpy.types import Operator +from bpy.types import Operator, PropertyGroup from bpy_extras.io_utils import ExportHelper -from bpy.props import StringProperty +from bpy.props import StringProperty, CollectionProperty, IntProperty, BoolProperty, EnumProperty MAX_WEDGE_COUNT = 65536 MAX_POINT_COUNT = 4294967296 @@ -58,6 +60,16 @@ class PskExporter(object): self.write_section(fp, b'RAWWEIGHTS', Psk.Weight, self.psk.weights) +def is_bone_filter_mode_item_available(context, identifier): + input_objects = PskBuilder.get_input_objects(context) + armature_object = input_objects.armature_object + if identifier == 'BONE_GROUPS': + if not armature_object.pose or not armature_object.pose.bone_groups: + return False + # else if... you can set up other conditions if you add more options + return True + + class PskExportOperator(Operator, ExportHelper): bl_idname = 'export.psk' bl_label = 'Export' @@ -73,17 +85,66 @@ class PskExportOperator(Operator, ExportHelper): def invoke(self, context, event): try: - PskBuilder.get_input_objects(context) + input_objects = PskBuilder.get_input_objects(context) except RuntimeError as e: self.report({'ERROR_INVALID_CONTEXT'}, str(e)) return {'CANCELLED'} + property_group = context.scene.psk_export + + # Populate bone groups list. + populate_bone_group_list(input_objects.armature_object, property_group.bone_group_list) + context.window_manager.fileselect_add(self) + return {'RUNNING_MODAL'} + def draw(self, context): + layout = self.layout + scene = context.scene + property_group = scene.psk_export + + # BONES + box = layout.box() + box.label(text='Bones', icon='BONE_DATA') + bone_filter_mode_items = property_group.bl_rna.properties['bone_filter_mode'].enum_items_static + row = box.row(align=True) + for item in bone_filter_mode_items: + identifier = item.identifier + item_layout = row.row(align=True) + item_layout.prop_enum(property_group, 'bone_filter_mode', item.identifier) + item_layout.enabled = is_bone_filter_mode_item_available(context, identifier) + + if property_group.bone_filter_mode == 'BONE_GROUPS': + row = box.row() + rows = max(3, min(len(property_group.bone_group_list), 10)) + row.template_list('PSX_UL_BoneGroupList', '', property_group, 'bone_group_list', property_group, 'bone_group_list_index', rows=rows) + def execute(self, context): + property_group = context.scene.psk_export builder = PskBuilder() - psk = builder.build(context) + options = PskBuilderOptions() + options.bone_group_indices = [x.index for x in property_group.bone_group_list if x.is_selected] + psk = builder.build(context, options) exporter = PskExporter(psk) exporter.export(self.filepath) return {'FINISHED'} + + +class PskExportPropertyGroup(PropertyGroup): + bone_filter_mode: EnumProperty( + name='Bone Filter', + description='', + items=( + ('ALL', 'All', 'All bones will be exported.'), + ('BONE_GROUPS', 'Bone Groups', 'Only bones belonging to the selected bone groups and their ancestors will be exported.') + ) + ) + bone_group_list: CollectionProperty(type=BoneGroupListItem) + bone_group_list_index: IntProperty(default=0) + + +__classes__ = [ + PskExportOperator, + PskExportPropertyGroup +] \ No newline at end of file diff --git a/io_export_psk_psa/types.py b/io_export_psk_psa/types.py new file mode 100644 index 0000000..47e6dcd --- /dev/null +++ b/io_export_psk_psa/types.py @@ -0,0 +1,25 @@ +from bpy.types import PropertyGroup, UIList +from bpy.props import StringProperty, IntProperty, BoolProperty + + +class PSX_UL_BoneGroupList(UIList): + def draw_item(self, context, layout, data, item, icon, active_data, active_propname, index): + layout.alignment = 'LEFT' + layout.prop(item, 'is_selected', icon_only=True) + layout.label(text=item.name, icon='GROUP_BONE' if item.index >= 0 else 'NONE') + + +class BoneGroupListItem(PropertyGroup): + name: StringProperty() + index: IntProperty() + is_selected: BoolProperty(default=False) + + @property + def name(self): + return self.name + + +__classes__ = [ + BoneGroupListItem, + PSX_UL_BoneGroupList +] From 41edd61f3db76e3c56dd01d75fb8d02963f73301 Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Sat, 22 Jan 2022 21:44:36 -0800 Subject: [PATCH 14/19] * Considerable clean-up of existing code. * Moved the PSA import to the properties panel. --- io_export_psk_psa/__init__.py | 36 ++-------- io_export_psk_psa/helpers.py | 2 +- io_export_psk_psa/psa/exporter.py | 12 +++- io_export_psk_psa/psa/importer.py | 112 +++++++++++++++++------------- io_export_psk_psa/psk/importer.py | 7 +- 5 files changed, 88 insertions(+), 81 deletions(-) diff --git a/io_export_psk_psa/__init__.py b/io_export_psk_psa/__init__.py index d29d0e4..de6c7be 100644 --- a/io_export_psk_psa/__init__.py +++ b/io_export_psk_psa/__init__.py @@ -42,33 +42,15 @@ else: from .psa import reader as psa_reader from .psa import importer as psa_importer + import bpy from bpy.props import PointerProperty - -# TODO: have the individual files emit a __classes__ field or something we can update it locally instead of explicitly declaring it here. -classes = [] -classes.extend(psx_types.__classes__) -classes.extend(psk_exporter.__classes__) -classes.extend([ - psk_importer.PskImportOperator, - psa_importer.PsaImportOperator, - psa_importer.PsaImportFileSelectOperator, - psa_exporter.PSA_UL_ExportActionList, - # psa_exporter.PSA_UL_ExportBoneGroupList, - psa_importer.PSA_UL_ImportActionList, - psa_importer.PsaImportActionListItem, - psa_importer.PsaImportPsaBoneItem, - psa_importer.PsaImportSelectAll, - psa_importer.PsaImportDeselectAll, - psa_importer.PSA_PT_ImportPanel, - psa_importer.PsaImportPropertyGroup, - psa_exporter.PsaExportOperator, - psa_exporter.PsaExportSelectAll, - psa_exporter.PsaExportDeselectAll, - psa_exporter.PsaExportActionListItem, - psa_exporter.PsaExportPropertyGroup, -]) +classes = psx_types.__classes__ + \ + psk_importer.__classes__ + \ + psk_exporter.__classes__ + \ + psa_exporter.__classes__ + \ + psa_importer.__classes__ def psk_export_menu_func(self, context): @@ -83,17 +65,12 @@ def psa_export_menu_func(self, context): self.layout.operator(psa_exporter.PsaExportOperator.bl_idname, text='Unreal PSA (.psa)') -def psa_import_menu_func(self, context): - self.layout.operator(psa_importer.PsaImportOperator.bl_idname, text='Unreal PSA (.psa)') - - def register(): for cls in classes: bpy.utils.register_class(cls) bpy.types.TOPBAR_MT_file_export.append(psk_export_menu_func) bpy.types.TOPBAR_MT_file_import.append(psk_import_menu_func) bpy.types.TOPBAR_MT_file_export.append(psa_export_menu_func) - bpy.types.TOPBAR_MT_file_import.append(psa_import_menu_func) bpy.types.Scene.psa_import = PointerProperty(type=psa_importer.PsaImportPropertyGroup) bpy.types.Scene.psa_export = PointerProperty(type=psa_exporter.PsaExportPropertyGroup) bpy.types.Scene.psk_export = PointerProperty(type=psk_exporter.PskExportPropertyGroup) @@ -105,7 +82,6 @@ def unregister(): bpy.types.TOPBAR_MT_file_export.remove(psk_export_menu_func) bpy.types.TOPBAR_MT_file_import.remove(psk_import_menu_func) bpy.types.TOPBAR_MT_file_export.remove(psa_export_menu_func) - bpy.types.TOPBAR_MT_file_import.remove(psa_import_menu_func) for cls in reversed(classes): bpy.utils.unregister_class(cls) diff --git a/io_export_psk_psa/helpers.py b/io_export_psk_psa/helpers.py index f8bcb4c..41f3c5b 100644 --- a/io_export_psk_psa/helpers.py +++ b/io_export_psk_psa/helpers.py @@ -1,7 +1,7 @@ from typing import List -def populate_bone_groups_list(armature_object, bone_group_list): +def populate_bone_group_list(armature_object, bone_group_list): bone_group_list.clear() item = bone_group_list.add() diff --git a/io_export_psk_psa/psa/exporter.py b/io_export_psk_psa/psa/exporter.py index 643a6e6..bd10552 100644 --- a/io_export_psk_psa/psa/exporter.py +++ b/io_export_psk_psa/psa/exporter.py @@ -155,7 +155,7 @@ class PsaExportOperator(Operator, ExportHelper): return {'CANCELLED'} # Populate bone groups list. - populate_bone_groups_list(self.armature, property_group.bone_group_list) + populate_bone_group_list(self.armature, property_group.bone_group_list) context.window_manager.fileselect_add(self) @@ -235,3 +235,13 @@ class PsaExportDeselectAll(bpy.types.Operator): for action in property_group.action_list: action.is_selected = False return {'FINISHED'} + + +__classes__ = [ + PsaExportActionListItem, + PsaExportPropertyGroup, + PsaExportOperator, + PSA_UL_ExportActionList, + PsaExportSelectAll, + PsaExportDeselectAll, +] diff --git a/io_export_psk_psa/psa/importer.py b/io_export_psk_psa/psa/importer.py index 996e96e..9d99131 100644 --- a/io_export_psk_psa/psa/importer.py +++ b/io_export_psk_psa/psa/importer.py @@ -1,6 +1,5 @@ import bpy import os -from math import inf import numpy as np from mathutils import Vector, Quaternion, Matrix from .data import Psa @@ -9,17 +8,14 @@ from bpy.types import Operator, Action, UIList, PropertyGroup, Panel, Armature, from bpy_extras.io_utils import ExportHelper, ImportHelper from bpy.props import StringProperty, BoolProperty, CollectionProperty, PointerProperty, IntProperty from .reader import PsaReader -import datetime class PsaImporter(object): def __init__(self): pass - def import_psa(self, psa_reader: PsaReader, sequence_names: List[AnyStr], context): - property_group = context.scene.psa_import + def import_psa(self, psa_reader: PsaReader, sequence_names: List[AnyStr], armature_object): sequences = map(lambda x: psa_reader.sequences[x], sequence_names) - armature_object = property_group.armature_object armature_data = armature_object.data class ImportBone(object): @@ -107,18 +103,8 @@ class PsaImporter(object): import_bone.orig_quat = armature_bone.matrix_local.to_quaternion() import_bone.post_quat = import_bone.orig_quat.conjugated() - io_time = datetime.timedelta() - math_time = datetime.timedelta() - keyframe_time = datetime.timedelta() - total_time = datetime.timedelta() - - total_datetime_start = datetime.datetime.now() - # Create and populate the data for new sequences. for sequence in sequences: - # F-curve data buffer for all bones. This is used later on to avoid adding redundant keyframes. - next_frame_bones_fcurve_data = [(inf, inf, inf, inf, inf, inf, inf)] * len(import_bones) - # Add the action. action = bpy.data.actions.new(name=sequence.name.decode()) @@ -142,10 +128,8 @@ class PsaImporter(object): sequence_name = sequence.name.decode('windows-1252') # Read the sequence data matrix from the PSA. - start_datetime = datetime.datetime.now() sequence_data_matrix = psa_reader.read_sequence_data_matrix(sequence_name) keyframe_write_matrix = np.ones(sequence_data_matrix.shape, dtype=np.int8) - io_time += datetime.datetime.now() - start_datetime # The first step is to determine the frames at which each bone will write out a keyframe. threshold = 0.001 @@ -173,21 +157,10 @@ class PsaImporter(object): # This bone has writeable keyframes for this frame. key_data = sequence_data_matrix[frame_index, bone_index] # Calculate the local-space key data for the bone. - start_datetime = datetime.datetime.now() fcurve_data = calculate_fcurve_data(import_bone, key_data) - math_time += datetime.datetime.now() - start_datetime for fcurve, should_write, datum in zip(import_bone.fcurves, keyframe_write_matrix[frame_index, bone_index], fcurve_data): if should_write: - start_datetime = datetime.datetime.now() fcurve.keyframe_points.insert(frame_index, datum, options={'FAST'}) - keyframe_time += datetime.datetime.now() - start_datetime - - total_time = datetime.datetime.now() - total_datetime_start - - print(f'io_time: {io_time}') - print(f'math_time: {math_time}') - print(f'keyframe_time: {keyframe_time}') - print(f'total_time: {total_time}') class PsaImportPsaBoneItem(PropertyGroup): @@ -209,6 +182,7 @@ class PsaImportActionListItem(PropertyGroup): def on_psa_file_path_updated(property, context): + print('PATH UPDATED') property_group = context.scene.psa_import property_group.action_list.clear() property_group.psa_bones.clear() @@ -242,9 +216,9 @@ def on_armature_object_updated(property, context): class PsaImportPropertyGroup(bpy.types.PropertyGroup): - psa_file_path: StringProperty(default='', subtype='FILE_PATH', update=on_psa_file_path_updated) + psa_file_path: StringProperty(default='', update=on_psa_file_path_updated) psa_bones: CollectionProperty(type=PsaImportPsaBoneItem) - armature_object: PointerProperty(name='Object', type=bpy.types.Object, update=on_armature_object_updated) + # armature_object: PointerProperty(name='Object', type=bpy.types.Object, update=on_armature_object_updated) action_list: CollectionProperty(type=PsaImportActionListItem) action_list_index: IntProperty(name='', default=0) action_filter_name: StringProperty(default='') @@ -320,35 +294,62 @@ class PsaImportDeselectAll(bpy.types.Operator): class PSA_PT_ImportPanel(Panel): - bl_space_type = 'NLA_EDITOR' - bl_region_type = 'UI' + bl_space_type = 'PROPERTIES' + bl_region_type = 'WINDOW' bl_label = 'PSA Import' - bl_context = 'object' + bl_context = 'data' bl_category = 'PSA Import' + bl_options = {'DEFAULT_CLOSED'} @classmethod def poll(cls, context): - return context.view_layer.objects.active is not None + return context.object.type == 'ARMATURE' def draw(self, context): layout = self.layout property_group = context.scene.psa_import + row = layout.row() - row.prop(property_group, 'psa_file_path', text='PSA File') + row.prop(property_group, 'psa_file_path', text='') + row.enabled = False + # row.enabled = property_group.psa_file_path is not '' row = layout.row() - row.prop_search(property_group, 'armature_object', bpy.data, 'objects') - box = layout.box() - box.label(text=f'Actions ({len(property_group.action_list)})', icon='ACTION') - row = box.row() - rows = max(3, min(len(property_group.action_list), 10)) - row.template_list('PSA_UL_ImportActionList', '', property_group, 'action_list', property_group, 'action_list_index', rows=rows) - row = box.row(align=True) - row.label(text='Select') - row.operator('psa_import.actions_select_all', text='All') - row.operator('psa_import.actions_deselect_all', text='None') + + layout.separator() + + row.operator('psa_import.select_file', text='Select PSA File', icon='FILEBROWSER') + if len(property_group.action_list) > 0: + box = layout.box() + box.label(text=f'Actions ({len(property_group.action_list)})', icon='ACTION') + row = box.row() + rows = max(3, min(len(property_group.action_list), 10)) + row.template_list('PSA_UL_ImportActionList', '', property_group, 'action_list', property_group, 'action_list_index', rows=rows) + row = box.row(align=True) + row.label(text='Select') + row.operator('psa_import.actions_select_all', text='All') + row.operator('psa_import.actions_deselect_all', text='None') + + layout.separator() + layout.operator('psa_import.import', text=f'Import') +class PsaImportSelectFile(Operator): + bl_idname = "psa_import.select_file" + bl_label = "Select" + bl_options = {'REGISTER', 'UNDO'} + filepath: bpy.props.StringProperty(subtype="FILE_PATH") + filter_glob: bpy.props.StringProperty(default="*.psa", options={"HIDDEN"}) + + def execute(self, context): + context.scene.psa_import.psa_file_path = self.filepath + return {"FINISHED"} + + def invoke(self, context, event): + context.window_manager.fileselect_add(self) + return {"RUNNING_MODAL"} + + class PsaImportOperator(Operator): bl_idname = 'psa_import.import' bl_label = 'Import' @@ -356,16 +357,17 @@ class PsaImportOperator(Operator): @classmethod def poll(cls, context): property_group = context.scene.psa_import + active_object = context.view_layer.objects.active action_list = property_group.action_list has_selected_actions = any(map(lambda action: action.is_selected, action_list)) - armature_object = property_group.armature_object - return has_selected_actions and armature_object is not None + return has_selected_actions and active_object is not None and active_object.type == 'ARMATURE' def execute(self, context): property_group = context.scene.psa_import psa_reader = PsaReader(property_group.psa_file_path) sequence_names = [x.action_name for x in property_group.action_list if x.is_selected] - PsaImporter().import_psa(psa_reader, sequence_names, context) + PsaImporter().import_psa(psa_reader, sequence_names, context.view_layer.objects.active) + self.report({'INFO'}, f'Imported {len(sequence_names)} action(s)') return {'FINISHED'} @@ -389,3 +391,17 @@ class PsaImportFileSelectOperator(Operator, ImportHelper): property_group.psa_file_path = self.filepath # Load the sequence names from the selected file return {'FINISHED'} + + +__classes__ = [ + PsaImportPsaBoneItem, + PsaImportActionListItem, + PsaImportPropertyGroup, + PSA_UL_ImportActionList, + PsaImportSelectAll, + PsaImportDeselectAll, + PSA_PT_ImportPanel, + PsaImportOperator, + PsaImportFileSelectOperator, + PsaImportSelectFile, +] diff --git a/io_export_psk_psa/psk/importer.py b/io_export_psk_psa/psk/importer.py index 1de4c7c..e651b0c 100644 --- a/io_export_psk_psa/psk/importer.py +++ b/io_export_psk_psa/psk/importer.py @@ -181,4 +181,9 @@ class PskImportOperator(Operator, ImportHelper): psk = reader.read(self.filepath) name = os.path.splitext(os.path.basename(self.filepath))[0] PskImporter().import_psk(psk, name, context) - return {'FINISHED'} \ No newline at end of file + return {'FINISHED'} + + +__classes__ = [ + PskImportOperator +] From a6c193e059a91f6599a2086c4296126ac45a4e07 Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Sat, 22 Jan 2022 23:40:36 -0800 Subject: [PATCH 15/19] More polishing (more operator descriptions, better error reporting etc.) --- io_export_psk_psa/helpers.py | 11 ++++++----- io_export_psk_psa/psa/exporter.py | 10 ++++++++-- io_export_psk_psa/psa/importer.py | 14 +++++++++----- io_export_psk_psa/psk/builder.py | 10 +++++++--- io_export_psk_psa/psk/exporter.py | 10 +++++++--- io_export_psk_psa/psk/importer.py | 2 +- 6 files changed, 38 insertions(+), 19 deletions(-) diff --git a/io_export_psk_psa/helpers.py b/io_export_psk_psa/helpers.py index 41f3c5b..34b74cb 100644 --- a/io_export_psk_psa/helpers.py +++ b/io_export_psk_psa/helpers.py @@ -9,11 +9,12 @@ def populate_bone_group_list(armature_object, bone_group_list): item.index = -1 item.is_selected = True - for bone_group_index, bone_group in enumerate(armature_object.pose.bone_groups): - item = bone_group_list.add() - item.name = bone_group.name - item.index = bone_group_index - item.is_selected = True + if armature_object and armature_object.pose: + for bone_group_index, bone_group in enumerate(armature_object.pose.bone_groups): + item = bone_group_list.add() + item.name = bone_group.name + item.index = bone_group_index + item.is_selected = True def add_bone_groups_to_layout(layout): diff --git a/io_export_psk_psa/psa/exporter.py b/io_export_psk_psa/psa/exporter.py index bd10552..3754b47 100644 --- a/io_export_psk_psa/psa/exporter.py +++ b/io_export_psk_psa/psa/exporter.py @@ -71,7 +71,7 @@ def is_bone_filter_mode_item_available(context, identifier): class PsaExportOperator(Operator, ExportHelper): bl_idname = 'export.psa' bl_label = 'Export' - __doc__ = 'PSA Exporter (.psa)' + __doc__ = 'Export actions to PSA' filename_ext = '.psa' filter_glob: StringProperty(default='*.psa', options={'HIDDEN'}) filepath: StringProperty( @@ -174,7 +174,11 @@ class PsaExportOperator(Operator, ExportHelper): options.bone_filter_mode = property_group.bone_filter_mode options.bone_group_indices = [x.index for x in property_group.bone_group_list if x.is_selected] builder = PsaBuilder() - psa = builder.build(context, options) + try: + psa = builder.build(context, options) + except RuntimeError as e: + self.report({'ERROR_INVALID_CONTEXT'}, str(e)) + return {'CANCELLED'} exporter = PsaExporter(psa) exporter.export(self.filepath) return {'FINISHED'} @@ -204,6 +208,7 @@ class PSA_UL_ExportActionList(UIList): class PsaExportSelectAll(bpy.types.Operator): bl_idname = 'psa_export.actions_select_all' bl_label = 'Select All' + bl_description = 'Select all actions' @classmethod def poll(cls, context): @@ -222,6 +227,7 @@ class PsaExportSelectAll(bpy.types.Operator): class PsaExportDeselectAll(bpy.types.Operator): bl_idname = 'psa_export.actions_deselect_all' bl_label = 'Deselect All' + bl_description = 'Deselect all actions' @classmethod def poll(cls, context): diff --git a/io_export_psk_psa/psa/importer.py b/io_export_psk_psa/psa/importer.py index 9d99131..620e24c 100644 --- a/io_export_psk_psa/psa/importer.py +++ b/io_export_psk_psa/psa/importer.py @@ -216,7 +216,7 @@ def on_armature_object_updated(property, context): class PsaImportPropertyGroup(bpy.types.PropertyGroup): - psa_file_path: StringProperty(default='', update=on_psa_file_path_updated) + psa_file_path: StringProperty(default='', update=on_psa_file_path_updated, name='PSA File Path') psa_bones: CollectionProperty(type=PsaImportPsaBoneItem) # armature_object: PointerProperty(name='Object', type=bpy.types.Object, update=on_armature_object_updated) action_list: CollectionProperty(type=PsaImportActionListItem) @@ -260,6 +260,7 @@ class PSA_UL_ImportActionList(UIList): class PsaImportSelectAll(bpy.types.Operator): bl_idname = 'psa_import.actions_select_all' bl_label = 'All' + bl_description = 'Select all actions' @classmethod def poll(cls, context): @@ -278,6 +279,7 @@ class PsaImportSelectAll(bpy.types.Operator): class PsaImportDeselectAll(bpy.types.Operator): bl_idname = 'psa_import.actions_deselect_all' bl_label = 'None' + bl_description = 'Deselect all actions' @classmethod def poll(cls, context): @@ -335,11 +337,12 @@ class PSA_PT_ImportPanel(Panel): class PsaImportSelectFile(Operator): - bl_idname = "psa_import.select_file" - bl_label = "Select" + bl_idname = 'psa_import.select_file' + bl_label = 'Select' bl_options = {'REGISTER', 'UNDO'} - filepath: bpy.props.StringProperty(subtype="FILE_PATH") - filter_glob: bpy.props.StringProperty(default="*.psa", options={"HIDDEN"}) + bl_description = 'Select a PSA file from which to import animations' + filepath: bpy.props.StringProperty(subtype='FILE_PATH') + filter_glob: bpy.props.StringProperty(default="*.psa", options={'HIDDEN'}) def execute(self, context): context.scene.psa_import.psa_file_path = self.filepath @@ -353,6 +356,7 @@ class PsaImportSelectFile(Operator): class PsaImportOperator(Operator): bl_idname = 'psa_import.import' bl_label = 'Import' + bl_description = 'Import the selected animations into the scene as actions' @classmethod def poll(cls, context): diff --git a/io_export_psk_psa/psk/builder.py b/io_export_psk_psa/psk/builder.py index f27bd12..c715f39 100644 --- a/io_export_psk_psa/psk/builder.py +++ b/io_export_psk_psa/psk/builder.py @@ -67,7 +67,8 @@ class PskBuilder(object): materials = OrderedDict() if armature_object is None: - # Static mesh (no armature) + # If the mesh has no armature object, simply assign it a dummy bone at the root to satisfy the requirement + # that a PSK file must have at least one bone. psk_bone = Psk.Bone() psk_bone.name = bytes('static', encoding='utf-8') psk_bone.flags = 0 @@ -79,13 +80,16 @@ class PskBuilder(object): else: bones = list(armature_object.data.bones) - # If bone groups are specified, get only the bones that are in the specified bone groups and their ancestors. - if len(options.bone_group_indices) > 0: + # If we are filtering by bone groups, get only the bones that are in the specified bone groups and their + # ancestors. + if options.bone_filter_mode == 'BONE_GROUPS': bone_indices = get_export_bone_indices_for_bone_groups(armature_object, options.bone_group_indices) bones = [bones[bone_index] for bone_index in bone_indices] # Ensure that the exported hierarchy has a single root bone. root_bones = [x for x in bones if x.parent is None] + print('root bones') + print(root_bones) if len(root_bones) > 1: root_bone_names = [x.name for x in bones] raise RuntimeError('Exported bone hierarchy must have a single root bone.' diff --git a/io_export_psk_psa/psk/exporter.py b/io_export_psk_psa/psk/exporter.py index 4e9b930..c9fdf90 100644 --- a/io_export_psk_psa/psk/exporter.py +++ b/io_export_psk_psa/psk/exporter.py @@ -64,7 +64,7 @@ def is_bone_filter_mode_item_available(context, identifier): input_objects = PskBuilder.get_input_objects(context) armature_object = input_objects.armature_object if identifier == 'BONE_GROUPS': - if not armature_object.pose or not armature_object.pose.bone_groups: + if not armature_object or not armature_object.pose or not armature_object.pose.bone_groups: return False # else if... you can set up other conditions if you add more options return True @@ -73,7 +73,7 @@ def is_bone_filter_mode_item_available(context, identifier): class PskExportOperator(Operator, ExportHelper): bl_idname = 'export.psk' bl_label = 'Export' - __doc__ = 'PSK Exporter (.psk)' + __doc__ = 'Export mesh and armature to PSK' filename_ext = '.psk' filter_glob: StringProperty(default='*.psk', options={'HIDDEN'}) @@ -125,7 +125,11 @@ class PskExportOperator(Operator, ExportHelper): builder = PskBuilder() options = PskBuilderOptions() options.bone_group_indices = [x.index for x in property_group.bone_group_list if x.is_selected] - psk = builder.build(context, options) + try: + psk = builder.build(context, options) + except RuntimeError as e: + self.report({'ERROR_INVALID_CONTEXT'}, str(e)) + return {'CANCELLED'} exporter = PskExporter(psk) exporter.export(self.filepath) return {'FINISHED'} diff --git a/io_export_psk_psa/psk/importer.py b/io_export_psk_psa/psk/importer.py index e651b0c..81283f8 100644 --- a/io_export_psk_psa/psk/importer.py +++ b/io_export_psk_psa/psk/importer.py @@ -167,7 +167,7 @@ class PskImporter(object): class PskImportOperator(Operator, ImportHelper): bl_idname = 'import.psk' bl_label = 'Export' - __doc__ = 'PSK Importer (.psk)' + __doc__ = 'Load a PSK file' filename_ext = '.psk' filter_glob: StringProperty(default='*.psk', options={'HIDDEN'}) filepath: StringProperty( From a636cf8f0e7727a14f21aca76baf2701427eaab2 Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Sat, 22 Jan 2022 23:46:19 -0800 Subject: [PATCH 16/19] Create README.md --- README.md | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 417f312..4e09b8a 100644 --- a/README.md +++ b/README.md @@ -15,15 +15,26 @@ This Blender add-on allows you to export meshes and animations to the [PSK and P 3. Navigate to File > Export > Unreal PSK (.psk) 4. Enter the file name and click "Export". +## Importing a PSK +1. Navigate to File > Import > Unreal PSK (.psk) +2. Select the PSK file you want to import and click "Import" + ## Exporting a PSA 1. Select the armature objects you wish to export. 2. Navigate to File > Export > Unreal PSA (.psa) 3. Enter the file name and click "Export". +## Importing a PSA +1. Select the armature object that you wish you import actions to. +2. Navigate to the Object Data Properties tab of the Properties editor. +3. Navigate to the PSA Import panel. +4. Click "Select PSA File". +5. Select the PSA file that you want to import animations from and click "Select". +6. In the Actions box, select which animations you want to import. +7. Click "Import". + # FAQ -## Can I use this addon to import PSK and PSA files? -Currently, no. +## Why are the mesh normals not accurate when importing a PSK extracted from [UE Viewer](https://www.gildor.org/en/projects/umodel)? +If preserving the mesh normals of models is important for your workflow, it is *not recommended* to export PSK files from UE Viewer. This is because UE Viewer makes no attempt to reconstruct the original [smoothing groups](https://en.wikipedia.org/wiki/Smoothing_group). As a result, the normals of imported PSK files will be incorrect when imported into Blender and will need to be manually fixed. -Presumably you are using this in concert with the [UE Viewer](https://www.gildor.org/en/projects/umodel) program to import extracted meshes. It is *not recommended* to export PSK/PSA from UE Viewer since it [does not preserve smoothing groups](https://github.com/gildor2/UEViewer/issues/235). As a result, the shading of imported models will be incorrect and will need to be manually fixed. Instead, it is recommended to export meshes to the glTF format for import into Blender since it preserves the correct mesh shading. - -Regardless, if you are dead set on using a PSK/PSA importer, use [this one](https://github.com/Befzz/blender3d_import_psk_psa). +As a workaround, it is recommended to export [glTF](https://en.wikipedia.org/wiki/GlTF) meshes out of UE Viewer instead, since the glTF format has support for explicit normals and UE Viewer can correctly preserve the mesh normals on export. Note, however, that the imported glTF armature may have it's bones oriented incorrectly when imported into blender. To mitigate this, you can combine the armature of PSK and the mesh of the glTF for best results. From 8be4b040f8edf47770a4818b77e03e34c0b739c8 Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Sat, 22 Jan 2022 23:54:15 -0800 Subject: [PATCH 17/19] Renaming the add-on from `io_export_psk_psa` to `io_scene_psk_psa` --- {io_export_psk_psa => io_scene_psk_psa}/__init__.py | 12 ++++++------ {io_export_psk_psa => io_scene_psk_psa}/data.py | 0 {io_export_psk_psa => io_scene_psk_psa}/helpers.py | 0 .../psa/__init__.py | 0 .../psa/builder.py | 0 {io_export_psk_psa => io_scene_psk_psa}/psa/data.py | 0 .../psa/exporter.py | 0 .../psa/importer.py | 0 .../psa/reader.py | 0 .../psk/__init__.py | 0 .../psk/builder.py | 0 {io_export_psk_psa => io_scene_psk_psa}/psk/data.py | 0 .../psk/exporter.py | 0 .../psk/importer.py | 0 .../psk/reader.py | 0 {io_export_psk_psa => io_scene_psk_psa}/types.py | 0 16 files changed, 6 insertions(+), 6 deletions(-) rename {io_export_psk_psa => io_scene_psk_psa}/__init__.py (89%) rename {io_export_psk_psa => io_scene_psk_psa}/data.py (100%) rename {io_export_psk_psa => io_scene_psk_psa}/helpers.py (100%) rename {io_export_psk_psa => io_scene_psk_psa}/psa/__init__.py (100%) rename {io_export_psk_psa => io_scene_psk_psa}/psa/builder.py (100%) rename {io_export_psk_psa => io_scene_psk_psa}/psa/data.py (100%) rename {io_export_psk_psa => io_scene_psk_psa}/psa/exporter.py (100%) rename {io_export_psk_psa => io_scene_psk_psa}/psa/importer.py (100%) rename {io_export_psk_psa => io_scene_psk_psa}/psa/reader.py (100%) rename {io_export_psk_psa => io_scene_psk_psa}/psk/__init__.py (100%) rename {io_export_psk_psa => io_scene_psk_psa}/psk/builder.py (100%) rename {io_export_psk_psa => io_scene_psk_psa}/psk/data.py (100%) rename {io_export_psk_psa => io_scene_psk_psa}/psk/exporter.py (100%) rename {io_export_psk_psa => io_scene_psk_psa}/psk/importer.py (100%) rename {io_export_psk_psa => io_scene_psk_psa}/psk/reader.py (100%) rename {io_export_psk_psa => io_scene_psk_psa}/types.py (100%) diff --git a/io_export_psk_psa/__init__.py b/io_scene_psk_psa/__init__.py similarity index 89% rename from io_export_psk_psa/__init__.py rename to io_scene_psk_psa/__init__.py index de6c7be..1a98c9b 100644 --- a/io_export_psk_psa/__init__.py +++ b/io_scene_psk_psa/__init__.py @@ -1,13 +1,13 @@ bl_info = { - "name": "PSK/PSA Exporter", + "name": "PSK/PSA Importer/Exporter", "author": "Colin Basnett", - "version": (1, 1, 1), + "version": (1, 2, 0), "blender": (2, 80, 0), - "location": "File > Export > PSK Export (.psk)", - "description": "PSK/PSA Export (.psk)", + # "location": "File > Export > PSK Export (.psk)", + "description": "PSK/PSA Import/Export (.psk/.psa)", "warning": "", - "wiki_url": "https://github.com/DarklightGames/io_export_psk_psa", - "tracker_url": "https://github.com/DarklightGames/io_export_psk_psa/issues", + "doc_url": "https://github.com/DarklightGames/io_scene_psk_psa", + "tracker_url": "https://github.com/DarklightGames/io_scene_psk_psa/issues", "category": "Import-Export" } diff --git a/io_export_psk_psa/data.py b/io_scene_psk_psa/data.py similarity index 100% rename from io_export_psk_psa/data.py rename to io_scene_psk_psa/data.py diff --git a/io_export_psk_psa/helpers.py b/io_scene_psk_psa/helpers.py similarity index 100% rename from io_export_psk_psa/helpers.py rename to io_scene_psk_psa/helpers.py diff --git a/io_export_psk_psa/psa/__init__.py b/io_scene_psk_psa/psa/__init__.py similarity index 100% rename from io_export_psk_psa/psa/__init__.py rename to io_scene_psk_psa/psa/__init__.py diff --git a/io_export_psk_psa/psa/builder.py b/io_scene_psk_psa/psa/builder.py similarity index 100% rename from io_export_psk_psa/psa/builder.py rename to io_scene_psk_psa/psa/builder.py diff --git a/io_export_psk_psa/psa/data.py b/io_scene_psk_psa/psa/data.py similarity index 100% rename from io_export_psk_psa/psa/data.py rename to io_scene_psk_psa/psa/data.py diff --git a/io_export_psk_psa/psa/exporter.py b/io_scene_psk_psa/psa/exporter.py similarity index 100% rename from io_export_psk_psa/psa/exporter.py rename to io_scene_psk_psa/psa/exporter.py diff --git a/io_export_psk_psa/psa/importer.py b/io_scene_psk_psa/psa/importer.py similarity index 100% rename from io_export_psk_psa/psa/importer.py rename to io_scene_psk_psa/psa/importer.py diff --git a/io_export_psk_psa/psa/reader.py b/io_scene_psk_psa/psa/reader.py similarity index 100% rename from io_export_psk_psa/psa/reader.py rename to io_scene_psk_psa/psa/reader.py diff --git a/io_export_psk_psa/psk/__init__.py b/io_scene_psk_psa/psk/__init__.py similarity index 100% rename from io_export_psk_psa/psk/__init__.py rename to io_scene_psk_psa/psk/__init__.py diff --git a/io_export_psk_psa/psk/builder.py b/io_scene_psk_psa/psk/builder.py similarity index 100% rename from io_export_psk_psa/psk/builder.py rename to io_scene_psk_psa/psk/builder.py diff --git a/io_export_psk_psa/psk/data.py b/io_scene_psk_psa/psk/data.py similarity index 100% rename from io_export_psk_psa/psk/data.py rename to io_scene_psk_psa/psk/data.py diff --git a/io_export_psk_psa/psk/exporter.py b/io_scene_psk_psa/psk/exporter.py similarity index 100% rename from io_export_psk_psa/psk/exporter.py rename to io_scene_psk_psa/psk/exporter.py diff --git a/io_export_psk_psa/psk/importer.py b/io_scene_psk_psa/psk/importer.py similarity index 100% rename from io_export_psk_psa/psk/importer.py rename to io_scene_psk_psa/psk/importer.py diff --git a/io_export_psk_psa/psk/reader.py b/io_scene_psk_psa/psk/reader.py similarity index 100% rename from io_export_psk_psa/psk/reader.py rename to io_scene_psk_psa/psk/reader.py diff --git a/io_export_psk_psa/types.py b/io_scene_psk_psa/types.py similarity index 100% rename from io_export_psk_psa/types.py rename to io_scene_psk_psa/types.py From 7527a43f8e800864adcc5a36da7d6fa5d79b5220 Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Sun, 23 Jan 2022 00:21:56 -0800 Subject: [PATCH 18/19] Updated README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4e09b8a..483e202 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -This Blender add-on allows you to export meshes and animations to the [PSK and PSA file formats](https://wiki.beyondunreal.com/PSK_%26_PSA_file_formats). +This Blender add-on allows you to import and export meshes and animations to the [PSK and PSA file formats](https://wiki.beyondunreal.com/PSK_%26_PSA_file_formats). # Installation 1. Download the zip file for the latest version from the [releases](https://github.com/DarklightGames/io_export_psk_psa/releases) page. @@ -7,7 +7,7 @@ This Blender add-on allows you to export meshes and animations to the [PSK and P 4. Select the "Add-ons" tab. 5. Click the "Install..." button. 6. Select the .zip file that you downloaded earlier and click "Install Add-on". -7. Enable the newly added "Import-Export: PSK/PSA Exporter" addon. +7. Enable the newly added "Import-Export: PSK/PSA Importer/Exporter" addon. # Usage ## Exporting a PSK From cb449f1c39faaa8afc999c5135c483f32ab352b2 Mon Sep 17 00:00:00 2001 From: Colin Basnett Date: Sun, 23 Jan 2022 00:22:07 -0800 Subject: [PATCH 19/19] Removed useless comments. --- io_scene_psk_psa/psa/builder.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/io_scene_psk_psa/psa/builder.py b/io_scene_psk_psa/psa/builder.py index 2f11438..825676a 100644 --- a/io_scene_psk_psa/psa/builder.py +++ b/io_scene_psk_psa/psa/builder.py @@ -9,10 +9,8 @@ class PsaBuilderOptions(object): self.bone_group_indices = [] -# https://git.cth451.me/cth451/blender-addons/blob/master/io_export_unreal_psk_psa.py class PsaBuilder(object): def __init__(self): - # TODO: add options in here (selected anims, eg.) pass def build(self, context, options: PsaBuilderOptions) -> Psa: