formatting

This commit is contained in:
jrkb 2025-05-13 16:08:53 +02:00
parent a681245093
commit ff85c93551
5 changed files with 641 additions and 549 deletions

View file

@ -1,13 +1,15 @@
import bpy
from bpy.props import (StringProperty,
BoolProperty,
EnumProperty,
IntProperty,
FloatProperty,
CollectionProperty)
from bpy.props import (
StringProperty,
BoolProperty,
EnumProperty,
IntProperty,
FloatProperty,
CollectionProperty,
)
from bpy.types import Operator
from bpy_extras.io_utils import ImportHelper, ExportHelper
from io_scene_gltf2 import ConvertGLTF2_Base
from io_scene_gltf2 import ConvertGLTF2_Base
import importlib
# then import dependencies for our addon
@ -22,43 +24,52 @@ else:
from .common import utils
# taken from blender_git/blender/scripts/addons/io_scene_gltf2/__init__.py
# taken from blender_git/blender/scripts/addons/io_scene_gltf2/__init__.py
def get_font_faces_in_file(filepath):
from io_scene_gltf2.io.imp.gltf2_io_gltf import glTFImporter, ImportError
try:
import_settings = { 'import_user_extensions': [] }
import_settings = {"import_user_extensions": []}
gltf_importer = glTFImporter(filepath, import_settings)
gltf_importer.read()
gltf_importer.checks()
out = []
for node in gltf_importer.data.nodes:
if type(node.extras) != type(None) \
and "glyph" in node.extras \
and not ("type" in node.extras and node.extras["type"] == "metrics") \
and not (f"{utils.prefix()}_type" in node.extras and node.extras[f"{utils.prefix()}_type"] == "metrics"):
if (
type(node.extras) != type(None)
and "glyph" in node.extras
and not ("type" in node.extras and node.extras["type"] == "metrics")
and not (
f"{utils.prefix()}_type" in node.extras
and node.extras[f"{utils.prefix()}_type"] == "metrics"
)
):
out.append(node.extras)
return out
except ImportError as e:
return None
# taken from blender_git/blender/scripts/addons/io_scene_gltf2/__init__.py
# taken from blender_git/blender/scripts/addons/io_scene_gltf2/__init__.py
class GetFontFacesInFile(Operator, ImportHelper):
"""Load a glTF 2.0 font and check which faces are in there"""
bl_idname = f"abc3d.check_font_gltf"
bl_label = 'Check glTF 2.0 Font'
bl_options = {'REGISTER', 'UNDO'}
bl_label = "Check glTF 2.0 Font"
bl_options = {"REGISTER", "UNDO"}
files: CollectionProperty(
name="File Path",
type=bpy.types.OperatorFileListElement,
)
# bpy.ops.abc3d.check_font_gltf(filepath="/home/jrkb/.config/blender/4.1/datafiles/abc3d/fonts/JRKB_LOL.glb")
# bpy.ops.abc3d.check_font_gltf(filepath="/home/jrkb/.config/blender/4.1/datafiles/abc3d/fonts/JRKB_LOL.glb")
found_fonts = []
def execute(self, context):
@ -70,96 +81,106 @@ class GetFontFacesInFile(Operator, ImportHelper):
if self.files:
# Multiple file check
ret = {'CANCELLED'}
ret = {"CANCELLED"}
dirname = os.path.dirname(self.filepath)
for file in self.files:
path = os.path.join(dirname, file.name)
if self.unit_check(path) == {'FINISHED'}:
ret = {'FINISHED'}
if self.unit_check(path) == {"FINISHED"}:
ret = {"FINISHED"}
return ret
else:
# Single file check
return self.unit_check(self.filepath)
def unit_check(self, filename):
self.found_fonts.append(["LOL","WHATEVER"])
return {'FINISHED'}
self.found_fonts.append(["LOL", "WHATEVER"])
return {"FINISHED"}
class ImportGLTF2(Operator, ConvertGLTF2_Base, ImportHelper):
"""Load a glTF 2.0 font"""
bl_idname = f"abc3d.import_font_gltf"
bl_label = 'Import glTF 2.0 Font'
bl_options = {'REGISTER', 'UNDO'}
filter_glob: StringProperty(default="*.glb;*.gltf", options={'HIDDEN'})
bl_idname = f"abc3d.import_font_gltf"
bl_label = "Import glTF 2.0 Font"
bl_options = {"REGISTER", "UNDO"}
filter_glob: StringProperty(default="*.glb;*.gltf", options={"HIDDEN"})
files: CollectionProperty(
name="File Path",
type=bpy.types.OperatorFileListElement,
)
loglevel: IntProperty(
name='Log Level',
description="Log Level")
loglevel: IntProperty(name="Log Level", description="Log Level")
import_pack_images: BoolProperty(
name='Pack Images',
description='Pack all images into .blend file',
default=True
name="Pack Images", description="Pack all images into .blend file", default=True
)
merge_vertices: BoolProperty(
name='Merge Vertices',
name="Merge Vertices",
description=(
'The glTF format requires discontinuous normals, UVs, and '
'other vertex attributes to be stored as separate vertices, '
'as required for rendering on typical graphics hardware. '
'This option attempts to combine co-located vertices where possible. '
'Currently cannot combine verts with different normals'
"The glTF format requires discontinuous normals, UVs, and "
"other vertex attributes to be stored as separate vertices, "
"as required for rendering on typical graphics hardware. "
"This option attempts to combine co-located vertices where possible. "
"Currently cannot combine verts with different normals"
),
default=False,
)
import_shading: EnumProperty(
name="Shading",
items=(("NORMALS", "Use Normal Data", ""),
("FLAT", "Flat Shading", ""),
("SMOOTH", "Smooth Shading", "")),
items=(
("NORMALS", "Use Normal Data", ""),
("FLAT", "Flat Shading", ""),
("SMOOTH", "Smooth Shading", ""),
),
description="How normals are computed during import",
default="NORMALS")
default="NORMALS",
)
bone_heuristic: EnumProperty(
name="Bone Dir",
items=(
("BLENDER", "Blender (best for import/export round trip)",
(
"BLENDER",
"Blender (best for import/export round trip)",
"Good for re-importing glTFs exported from Blender, "
"and re-exporting glTFs to glTFs after Blender editing. "
"Bone tips are placed on their local +Y axis (in glTF space)"),
("TEMPERANCE", "Temperance (average)",
"Bone tips are placed on their local +Y axis (in glTF space)",
),
(
"TEMPERANCE",
"Temperance (average)",
"Decent all-around strategy. "
"A bone with one child has its tip placed on the local axis "
"closest to its child"),
("FORTUNE", "Fortune (may look better, less accurate)",
"closest to its child",
),
(
"FORTUNE",
"Fortune (may look better, less accurate)",
"Might look better than Temperance, but also might have errors. "
"A bone with one child has its tip placed at its child's root. "
"Non-uniform scalings may get messed up though, so beware"),
"Non-uniform scalings may get messed up though, so beware",
),
),
description="Heuristic for placing bones. Tries to make bones pretty",
default="BLENDER",
)
guess_original_bind_pose: BoolProperty(
name='Guess Original Bind Pose',
name="Guess Original Bind Pose",
description=(
'Try to guess the original bind pose for skinned meshes from '
'the inverse bind matrices. '
'When off, use default/rest pose as bind pose'
"Try to guess the original bind pose for skinned meshes from "
"the inverse bind matrices. "
"When off, use default/rest pose as bind pose"
),
default=True,
)
import_webp_texture: BoolProperty(
name='Import WebP textures',
name="Import WebP textures",
description=(
"If a texture exists in WebP format, "
"loads the WebP texture instead of the fallback PNG/JPEG one"
@ -168,7 +189,7 @@ class ImportGLTF2(Operator, ConvertGLTF2_Base, ImportHelper):
)
glyphs: StringProperty(
name='Import only these glyphs',
name="Import only these glyphs",
description=(
"Loading glyphs is expensive, if the meshes are huge"
"So we can filter all glyphs out that we do not want"
@ -197,25 +218,32 @@ class ImportGLTF2(Operator, ConvertGLTF2_Base, ImportHelper):
layout.use_property_split = True
layout.use_property_decorate = False # No animation.
layout.prop(self, 'import_pack_images')
layout.prop(self, 'merge_vertices')
layout.prop(self, 'import_shading')
layout.prop(self, 'guess_original_bind_pose')
layout.prop(self, 'bone_heuristic')
layout.prop(self, 'export_import_convert_lighting_mode')
layout.prop(self, 'import_webp_texture')
layout.prop(self, "import_pack_images")
layout.prop(self, "merge_vertices")
layout.prop(self, "import_shading")
layout.prop(self, "guess_original_bind_pose")
layout.prop(self, "bone_heuristic")
layout.prop(self, "export_import_convert_lighting_mode")
layout.prop(self, "import_webp_texture")
def invoke(self, context, event):
import sys
preferences = bpy.context.preferences
for addon_name in preferences.addons.keys():
try:
if hasattr(sys.modules[addon_name], 'glTF2ImportUserExtension') or hasattr(sys.modules[addon_name], 'glTF2ImportUserExtensions'):
importer_extension_panel_unregister_functors.append(sys.modules[addon_name].register_panel())
if hasattr(
sys.modules[addon_name], "glTF2ImportUserExtension"
) or hasattr(sys.modules[addon_name], "glTF2ImportUserExtensions"):
importer_extension_panel_unregister_functors.append(
sys.modules[addon_name].register_panel()
)
except Exception:
pass
self.has_active_importer_extensions = len(importer_extension_panel_unregister_functors) > 0
self.has_active_importer_extensions = (
len(importer_extension_panel_unregister_functors) > 0
)
return ImportHelper.invoke(self, context, event)
def execute(self, context):
@ -230,25 +258,26 @@ class ImportGLTF2(Operator, ConvertGLTF2_Base, ImportHelper):
user_extensions = []
import sys
preferences = bpy.context.preferences
for addon_name in preferences.addons.keys():
try:
module = sys.modules[addon_name]
except Exception:
continue
if hasattr(module, 'glTF2ImportUserExtension'):
if hasattr(module, "glTF2ImportUserExtension"):
extension_ctor = module.glTF2ImportUserExtension
user_extensions.append(extension_ctor())
import_settings['import_user_extensions'] = user_extensions
import_settings["import_user_extensions"] = user_extensions
if self.files:
# Multiple file import
ret = {'CANCELLED'}
ret = {"CANCELLED"}
dirname = os.path.dirname(self.filepath)
for file in self.files:
path = os.path.join(dirname, file.name)
if self.unit_import(path, import_settings) == {'FINISHED'}:
ret = {'FINISHED'}
if self.unit_import(path, import_settings) == {"FINISHED"}:
ret = {"FINISHED"}
return ret
else:
# Single file import
@ -308,18 +337,31 @@ class ImportGLTF2(Operator, ConvertGLTF2_Base, ImportHelper):
# indeed representing a glyph we want
for node in gltf.data.nodes:
# :-O woah
if type(node.extras) != type(None) \
and "glyph" in node.extras \
and (node.extras["glyph"] in self.glyphs \
or len(self.glyphs) == 0) \
and (self.font_name == "" or \
( "font_name" in node.extras \
and (node.extras["font_name"] in self.font_name \
or len(self.glyphs) == 0))) \
and (self.face_name == "" or \
( "face_name" in node.extras \
and (node.extras["face_name"] in self.face_name \
or len(self.glyphs) == 0))):
if (
type(node.extras) != type(None)
and "glyph" in node.extras
and (node.extras["glyph"] in self.glyphs or len(self.glyphs) == 0)
and (
self.font_name == ""
or (
"font_name" in node.extras
and (
node.extras["font_name"] in self.font_name
or len(self.glyphs) == 0
)
)
)
and (
self.face_name == ""
or (
"face_name" in node.extras
and (
node.extras["face_name"] in self.face_name
or len(self.glyphs) == 0
)
)
)
):
# if there is a match, add the node incl children ..
add_node(node)
# .. and their parents recursively
@ -355,7 +397,7 @@ class ImportGLTF2(Operator, ConvertGLTF2_Base, ImportHelper):
# and some have different indices
for node in nodes:
if type(node.children) != type(None):
children = [] # brand new children
children = [] # brand new children
for i, c in enumerate(node.children):
# check if children are lost
if c in node_indices:
@ -399,23 +441,26 @@ class ImportGLTF2(Operator, ConvertGLTF2_Base, ImportHelper):
vnode = gltf.vnodes[vi]
if vnode.type == VNode.Object:
if vnode.parent is not None:
if not hasattr(gltf.vnodes[vnode.parent],
"blender_object"):
create_blender_object(gltf,
vnode.parent,
nodes)
if not hasattr(vnode,
"blender_object"):
if not hasattr(gltf.vnodes[vnode.parent], "blender_object"):
create_blender_object(gltf, vnode.parent, nodes)
if not hasattr(vnode, "blender_object"):
obj = BlenderNode.create_object(gltf, vi)
obj["font_import"] = True
n_vars = vars(nodes[vi])
if "extras" in n_vars:
set_extras(obj, n_vars["extras"])
if "glyph" in n_vars["extras"] and \
not ("type" in n_vars["extras"] and \
n_vars["extras"]["type"] == "metrics") and \
not (f"{utils.prefix()}_type" in n_vars["extras"] and \
n_vars["extras"][f"{utils.prefix()}_type"] == "metrics"):
if (
"glyph" in n_vars["extras"]
and not (
"type" in n_vars["extras"]
and n_vars["extras"]["type"] == "metrics"
)
and not (
f"{utils.prefix()}_type" in n_vars["extras"]
and n_vars["extras"][f"{utils.prefix()}_type"]
== "metrics"
)
):
obj["type"] = "glyph"
for vi, vnode in gltf.vnodes.items():
@ -432,14 +477,15 @@ class ImportGLTF2(Operator, ConvertGLTF2_Base, ImportHelper):
if hasattr(gltf.log.logger, "removeHandler"):
gltf.log.logger.removeHandler(gltf.log_handler)
return {'FINISHED'}
return {"FINISHED"}
except ImportError as e:
self.report({'ERROR'}, e.args[0])
return {'CANCELLED'}
self.report({"ERROR"}, e.args[0])
return {"CANCELLED"}
def set_debug_log(self):
import logging
if bpy.app.debug_value == 0:
self.loglevel = logging.CRITICAL
elif bpy.app.debug_value == 1: