remove uv modifier from bld_mesh.py and finish flatten uv and rail uv

This commit is contained in:
yyc12345 2023-10-23 10:57:29 +08:00
parent f7dd5f32ba
commit 9079bf1bb3
5 changed files with 308 additions and 153 deletions

View File

@ -1,4 +1,7 @@
import bpy, mathutils, bmesh
from . import UTIL_virtools_types
#region Param Struct
class _FlattenParamBySize():
mScaleSize: float
@ -30,6 +33,8 @@ class _FlattenParam():
def CreateByRefPoint(cls, ref_point: int, ref_point_uv: float):
return cls(True, _FlattenParamByRefPoint(ref_point, ref_point_uv))
#endregion
class BBP_OT_flatten_uv(bpy.types.Operator):
"""Flatten selected face UV. Only works for convex face"""
bl_idname = "bbp.flatten_uv"
@ -102,8 +107,15 @@ class BBP_OT_flatten_uv(bpy.types.Operator):
scale_data: _FlattenParam = _FlattenParam.CreateByRefPoint(self.reference_point, self.reference_uv)
# do flatten uv and report
no_processed_count = _real_flatten_uv(bpy.context.active_object.data,
self.reference_edge, scale_data)
# sync data first
# ref: https://blender.stackexchange.com/questions/218086/data-vertices-returns-an-empty-collection-in-edit-mode
this_obj: bpy.types.Object = bpy.context.active_object
this_obj.update_from_editmode()
no_processed_count = _real_flatten_uv(
this_obj.data,
self.reference_edge,
scale_data
)
if no_processed_count != 0:
print("[Flatten UV] {} faces are not be processed correctly because process failed."
.format(no_processed_count))
@ -127,39 +139,72 @@ class BBP_OT_flatten_uv(bpy.types.Operator):
layout.prop(self, "reference_point")
layout.prop(self, "reference_uv")
def _real_flatten_uv(mesh: bpy.types.Mesh, reference_edge: int,
scale_data: _FlattenParam) -> int:
#region Real Worker Functions
def _set_face_vertex_uv(face: bmesh.types.BMFace, uv_layer: bmesh.types.BMLayerItem, idx: int, uv: UTIL_virtools_types.ConstVxVector2) -> None:
"""
Help function to set UV data for face.
@param face[in] The face to be set.
@param uv_layer[in] The corresponding uv layer. Hint: it was gotten from BMesh.loops.layers.uv.verify()
@param idx[in] The index of trying setting vertex.
@param uv[in] The set UV data
"""
face.loops[idx][uv_layer].uv = uv
def _get_face_vertex_pos(face: bmesh.types.BMFace, idx: int) -> UTIL_virtools_types.ConstVxVector3:
"""
Help function to get vertex position from face by provided index.
No index overflow checker. Caller must make sure the provided index is not overflow.
@param face[in] Bmesh face struct.
@param idx[in] The index of trying getting vertex.
@return The gotten vertex position.
"""
v: mathutils.Vector = face.loops[idx].vert.co
return (v[0], v[1], v[2])
def _circular_clamp_index(v: int, vmax: int) -> int:
"""
Circular clamp face vertex index.
Used by _real_flatten_uv.
@param v[in] The index to clamp
@param vmax[in] The count of used face vertex. At least 3.
@return The circular clamped value ranging from 0 to vmax.
"""
return v % vmax
def _real_flatten_uv(mesh: bpy.types.Mesh, reference_edge: int, scale_data: _FlattenParam) -> int:
no_processed_count: int = 0
# if no uv, create it
if mesh.uv_layers.active is None:
mesh.uv_layers.new(do_init = False)
# create bmesh
# create bmesh modifier
bm: bmesh.types.BMesh = bmesh.from_edit_mesh(mesh)
# NOTE: Blender 3.5 change mesh underlying data struct.
# Originally this section also need to be update ad Blender 3.5 style
# But this is a part of bmesh. This struct is not changed so we don't need update it.
uv_lay: bmesh.types.BMLayerItem = bm.loops.layers.uv.active
# use verify() to make sure there is a uv layer to write data
# verify() will return existing one or create one if no layer existing.
uv_layers: bmesh.types.BMLayerCollection = bm.loops.layers.uv
uv_layer: bmesh.types.BMLayerItem = uv_layers.verify()
# process each face
face: bmesh.types.BMFace
for face in bm.faces:
# ========== only process selected face ==========
# ===== check requirement =====
# check whether face selected
# only process selected face
if not face.select:
continue
# ========== resolve reference edge and point ==========
# ===== resolve reference edge and point =====
# check reference validation
allPoint: int = len(face.loops)
if reference_edge >= allPoint: # reference edge overflow
all_point: int = len(face.loops)
if reference_edge >= all_point: # reference edge overflow
no_processed_count += 1
continue
# check scale validation
if scale_data.mUseRefPoint:
if ((scale_data.mParamData.mReferencePoint <= 1) # reference point too low
or (scale_data.mParamData.mReferencePoint
>= allPoint)): # reference point overflow
or (scale_data.mParamData.mReferencePoint >= all_point)): # reference point overflow
no_processed_count += 1
continue
else:
@ -181,20 +226,10 @@ def _real_flatten_uv(mesh: bpy.types.Mesh, reference_edge: int,
# just a weird uv. user will notice this problem.
# get point
p1Relative: int = reference_edge
p2Relative: int = reference_edge + 1
p3Relative: int = reference_edge + 2
if p2Relative >= allPoint:
p2Relative -= allPoint
if p3Relative >= allPoint:
p3Relative -= allPoint
p1: mathutils.Vector = mathutils.Vector(
tuple(face.loops[p1Relative].vert.co[x] for x in range(3)))
p2: mathutils.Vector = mathutils.Vector(
tuple(face.loops[p2Relative].vert.co[x] for x in range(3)))
p3: mathutils.Vector = mathutils.Vector(
tuple(face.loops[p3Relative].vert.co[x] for x in range(3)))
pidx_start: int = _circular_clamp_index(reference_edge, all_point)
p1: mathutils.Vector = mathutils.Vector(_get_face_vertex_pos(face, pidx_start))
p2: mathutils.Vector = mathutils.Vector(_get_face_vertex_pos(face, _circular_clamp_index(reference_edge + 1, all_point)))
p3: mathutils.Vector = mathutils.Vector(_get_face_vertex_pos(face, _circular_clamp_index(reference_edge + 2, all_point)))
# get y axis
new_y_axis: mathutils.Vector = p2 - p1
@ -205,8 +240,7 @@ def _real_flatten_uv(mesh: bpy.types.Mesh, reference_edge: int,
# get z axis
new_z_axis: mathutils.Vector = new_y_axis.cross(vec1)
new_z_axis.normalize()
if not any(round(v, 7) for v in new_z_axis
): # if z is a zero vector, use face normal instead
if not any(round(v, 7) for v in new_z_axis): # if z is a zero vector, use face normal instead
new_z_axis = face.normal.normalized()
# get x axis
@ -228,25 +262,24 @@ def _real_flatten_uv(mesh: bpy.types.Mesh, reference_edge: int,
transition_matrix: mathutils.Matrix = origin_base @ new_base
transition_matrix.invert_safe()
# ========== rescale correction ==========
# ===== rescale correction =====
rescale: float = 0.0
if scale_data.mUseRefPoint:
# ref point method
# get reference point from loop
refpRelative: int = p1Relative + scale_data.mParamData.mReferencePoint
if refpRelative >= allPoint:
refpRelative -= allPoint
pRef: mathutils.Vector = mathutils.Vector(tuple(face.loops[refpRelative].vert.co[x] for x in range(3))) - p1
pidx_refp: int = _circular_clamp_index(pidx_start + scale_data.mParamData.mReferencePoint, all_point)
pref: mathutils.Vector = mathutils.Vector(_get_face_vertex_pos(face, pidx_refp)) - p1
# calc its U component
vec_u: float = abs((transition_matrix @ pRef).x)
vec_u: float = abs((transition_matrix @ pref).x)
if round(vec_u, 7) == 0.0:
rescale: float = 1.0 # fallback. rescale = 1 will not affect anything
rescale = 1.0 # fallback. rescale = 1 will not affect anything
else:
rescale: float = scale_data.mParamData.mReferenceUV / vec_u
rescale = scale_data.mParamData.mReferenceUV / vec_u
else:
# scale size method
# apply rescale directly
rescale: float = 1.0 / scale_data.mParamData.mScaleSize
rescale = 1.0 / scale_data.mParamData.mScaleSize
# construct matrix
# we only rescale U component (X component)
@ -260,18 +293,19 @@ def _real_flatten_uv(mesh: bpy.types.Mesh, reference_edge: int,
rescale_transition_matrix: mathutils.Matrix = scale_matrix @ transition_matrix
# ========== process each face ==========
for loop_index in range(allPoint):
pp: mathutils.Vector = mathutils.Vector(tuple(face.loops[loop_index].vert.co[x] for x in range(3))) - p1
for idx in range(all_point):
pp: mathutils.Vector = mathutils.Vector(_get_face_vertex_pos(face, idx)) - p1
ppuv: mathutils.Vector = rescale_transition_matrix @ pp
# u and v component has been calculated properly. no extra process needed.
# just get abs for the u component
face.loops[loop_index][uv_lay].uv = (abs(ppuv.x), ppuv.y)
_set_face_vertex_uv(face, uv_layer, idx, (abs(ppuv.x), ppuv.y))
# sync the result to view port
bmesh.update_edit_mesh(mesh)
# return process result
return no_processed_count
#endregion
def register() -> None:
bpy.utils.register_class(BBP_OT_flatten_uv)

View File

@ -0,0 +1,213 @@
import bpy, bmesh, mathutils
import typing
from . import UTIL_virtools_types, UTIL_icons_manager, UTIL_functions
#region Material Pointer Property Resolver
class BBPRailUVPatch(bpy.types.PropertyGroup):
rail_mtl: bpy.props.PointerProperty(
name = "Material",
description = "The material used for rail",
type = bpy.types.Material,
)
def get_rail_uv_patch() -> BBPRailUVPatch:
return bpy.context.scene.bbp_rail_uv_patch
def get_raw_rail_uv_patch() -> bpy.types.Material:
return get_rail_uv_patch().rail_mtl
def draw_rail_uv_patch(layout: bpy.types.UILayout) -> None:
layout.prop(get_rail_uv_patch(), 'rail_mtl')
#endregion
class BBP_OT_rail_uv(bpy.types.Operator):
"""Create UV for Rail as Ballance Showen (TT_ReflectionMapping)"""
bl_idname = "bbp.rail_uv"
bl_label = "Create Rail UV"
bl_options = {'UNDO'}
@classmethod
def poll(self, context):
return _check_rail_target()
def invoke(self, context, event):
wm: bpy.types.WindowManager = context.window_manager
return wm.invoke_props_dialog(self)
def execute(self, context):
# check material
mtl: bpy.types.Material = get_raw_rail_uv_patch()
if mtl is None:
UTIL_functions.message_box(
("No specific material", ),
"Lost Parameter",
UTIL_icons_manager.BlenderPresetIcons.Error.value
)
return {'CANCELLED'}
# apply rail uv
_create_rail_uv(_get_rail_target(), mtl)
return {'FINISHED'}
def draw(self, context):
layout: bpy.types.UILayout = self.layout
draw_rail_uv_patch(layout)
#region Real Worker Functions
def _check_rail_target() -> bool:
for obj in bpy.context.selected_objects:
if obj.type != 'MESH':
continue
if obj.mode != 'OBJECT':
continue
if obj.data is None:
continue
return True
return False
def _get_rail_target() -> typing.Iterable[bpy.types.Mesh]:
# collect objects
meshes: list[bpy.types.Mesh] = []
error_objname: list[str] = []
for obj in bpy.context.selected_objects:
if obj.type != 'MESH':
error_objname.append(obj.name)
continue
if obj.mode != 'OBJECT':
error_objname.append(obj.name)
continue
if obj.data is None:
error_objname.append(obj.name)
continue
meshes.append(obj.data)
# display warning window if necessary
if len(error_objname) != 0:
# show dialog
UTIL_functions.message_box(
("Some objects is not processed, see Console for more infos.", ),
"Object Type Warning",
UTIL_icons_manager.BlenderPresetIcons.Warning.value
)
# output to console
print('')
print('=====')
print('Following objects are not processed by Rail UV because they do not meet the requirements of Rail UV.')
for objname in error_objname:
print(objname)
print('=====')
print('')
# return valid
return meshes
def _tt_reflection_mapping_compute(
point_: UTIL_virtools_types.ConstVxVector3,
nml_: UTIL_virtools_types.ConstVxVector3,
refobj_: UTIL_virtools_types.ConstVxVector3) -> UTIL_virtools_types.ConstVxVector2:
# switch blender coord to virtools coord for convenient calc
point: mathutils.Vector = mathutils.Vector((point_[0], point_[2], point_[1]))
nml: mathutils.Vector = mathutils.Vector((nml_[0], nml_[2], nml_[1])).normalized()
refobj: mathutils.Vector = mathutils.Vector((refobj_[0], refobj_[2], refobj_[1]))
p: mathutils.Vector = (refobj - point).normalized()
b: mathutils.Vector = (((2 * (p * nml)) * nml) - p)
b.normalize()
# convert back to blender coord
return ((b.x + 1.0) / 2.0, -(b.z + 1.0) / 2.0)
def _set_face_vertex_uv(face: bpy.types.MeshPolygon, uv_layer: bpy.types.MeshUVLoopLayer, idx: int, uv: UTIL_virtools_types.ConstVxVector2) -> None:
"""
Help function to set face vertex uv by index.
@param face[in] The face to be set.
@param uv_layer[in] The uv layer to be set gotten from `Mesh.uv_layers.active`
@param idx[in] The index related to face to set uv.
@param uv[in] The uv data.
"""
uv_layer.uv[face.loop_start + idx].vector = uv
def _get_face_vertex_pos(face: bpy.types.MeshPolygon, loops: bpy.types.MeshLoops, vecs: bpy.types.MeshVertices, idx: int) -> UTIL_virtools_types.ConstVxVector3:
"""
Help function. Get face referenced vertex position data by index
@param face[in] The face to be set.
@param loops[in] Mesh loops gotten from `Mesh.loops`
@param vecs[in] Mesh vertices gotten from `Mesh.vertices`
@param idx[in] The index related to face to get position.
"""
v: mathutils.Vector = vecs[loops[face.loop_start + idx].vertex_index].co
return (v[0], v[1], v[2])
def _get_face_vertex_nml(face: bpy.types.MeshPolygon, loops: bpy.types.MeshLoops, idx: int) -> UTIL_virtools_types.ConstVxVector3:
"""
Help function to get face vertex normal.
Similar to _get_face_vertex_pos, just get normal, not position.
@param face[in] The face to be set.
@param loops[in] Mesh loops gotten from `Mesh.loops`
@param idx[in] The index related to face to get normal.
"""
v: mathutils.Vector = loops[face.loop_start + idx].normal
return (v[0], v[1], v[2])
def _get_face_vertex_count(face: bpy.types.MeshPolygon) -> int:
"""
Help function to get how many vertex used by this face.
@return The count of used vertex. At least 3.
"""
return face.loop_total
def _create_rail_uv(meshes: typing.Iterable[bpy.types.Mesh], mtl: bpy.types.Material):
for mesh in meshes:
# clean it material and set rail first
mesh.materials.clear()
mesh.materials.append(mtl)
# and validate face mtl idx ref
mesh.validate_material_indices()
# get uv and make sure at least one uv
if mesh.uv_layers.active is None:
mesh.uv_layers.new(do_init = False)
uv_layer: bpy.types.MeshUVLoopLayer = mesh.uv_layers.active
# get other useful data
loops: bpy.types.MeshLoops = mesh.loops
vecs: bpy.types.MeshVertices = mesh.vertices
refobj: UTIL_virtools_types.ConstVxVector3 = (0.0, 0.0, 0.0)
for face in mesh.polygons:
for idx in range(_get_face_vertex_count(face)):
_set_face_vertex_uv(
face,
uv_layer,
idx,
_tt_reflection_mapping_compute(
_get_face_vertex_pos(face, loops, vecs, idx),
_get_face_vertex_nml(face, loops, idx),
refobj
)
)
#endregion
def register() -> None:
# register patch first
bpy.utils.register_class(BBPRailUVPatch)
bpy.types.Scene.bbp_rail_uv_patch = bpy.props.PointerProperty(type = BBPRailUVPatch)
bpy.utils.register_class(BBP_OT_rail_uv)
def unregister() -> None:
del bpy.types.Scene.bbp_rail_uv_patch
bpy.utils.unregister_class(BBP_OT_rail_uv)

View File

@ -103,58 +103,6 @@ class TemporaryMesh():
raise UTIL_functions.BBPException('try calling invalid TemporaryMesh.')
return self.__mTempMesh
class FaceForModifyingUV():
"""
This class do not have invalid mesh exception checker.
Because MeshUVModifier will make sure this sub class will not throw any error
"""
__mMeshVertices: bpy.types.MeshVertices
__mMeshUVs: bpy.types.MeshUVLoopLayer
__mMeshLoops: bpy.types.MeshLoops
__mMeshPolygon: bpy.types.MeshPolygon
def __init__(self, mesh: bpy.types.Mesh):
self.__mMeshVertices = mesh.vertices
self.__mMeshUVs = mesh.uv_layers.active
self.__mMeshLoops = mesh.loops
def _set_face(self, poly: bpy.types.MeshPolygon) -> None:
"""
Only should be called by MeshUVModifier
"""
self.__mMeshPolygon = poly
def is_face_selected(self) -> bool:
return self.__mMeshPolygon.select
def get_face_normal(self) -> UTIL_virtools_types.ConstVxVector3:
nml: mathutils.Vector = self.__mMeshPolygon.normal
return (nml.x, nml.y, nml.z)
def get_face_vertex_count(self) -> int:
return self.__mMeshPolygon.loop_total
def get_face_vertex_pos_by_index(self, index: int) -> UTIL_virtools_types.ConstVxVector3:
if index < 0 or index >= self.__mMeshPolygon.loop_total:
raise UTIL_functions.BBPException('invalid index for getting face vertex position.')
v: mathutils.Vector = self.__mMeshVertices[self.__mMeshPolygon.loop_start + index].co
return (v.x, v.y, v.z)
def get_face_vertex_nml_by_index(self, index: int) -> UTIL_virtools_types.ConstVxVector3:
if index < 0 or index >= self.__mMeshPolygon.loop_total:
raise UTIL_functions.BBPException('invalid index for getting face vertex position.')
v: mathutils.Vector = self.__mMeshLoops[self.__mMeshPolygon.loop_start + index].normal
return (v.x, v.y, v.z)
def set_face_vertex_uv_by_index(self, index: int, v: UTIL_virtools_types.ConstVxVector2) -> None:
if index < 0 or index >= self.__mMeshPolygon.loop_total:
raise UTIL_functions.BBPException('invalid index for getting face vertex position.')
self.__mMeshUVs.uv[self.__mMeshPolygon.loop_start + index].vector = (v[0], v[1])
#endregion
class MeshReader():
@ -495,7 +443,7 @@ class MeshWriter():
list(_flat_face_nml_index(self.__mFaceNmlIndices, self.__mVertexNormal))
)
# add face vertex uv by function
self.__mAssocMesh.uv_layers[0].uv.foreach_set('vector',
self.__mAssocMesh.uv_layers.active.uv.foreach_set('vector',
list(_flat_face_uv_index(self.__mFaceUvIndices, self.__mVertexUV))
) # NOTE: blender 3.5 changed. UV must be visited by .uv, not the .data
@ -540,52 +488,3 @@ class MeshWriter():
self.__mAssocMesh.clear_geometry()
# clear mtl slot because clear_geometry will not do this.
self.__mAssocMesh.materials.clear()
class MeshUVModifier():
"""
"""
__mAssocMesh: bpy.types.Mesh | None
def __init__(self, mesh: bpy.types.Mesh):
self.__mAssocMesh = mesh
if self.is_valid():
# make sure there is a exist uv layer for editing
if self.__mAssocMesh.uv_layers.active is None:
self.__mAssocMesh.uv_layers.new(do_init = False)
# split face normal
self.__mAssocMesh.calc_normals_split()
def is_valid(self) -> bool:
return self.__mAssocMesh is not None
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.dispose()
def dispose(self) -> None:
if self.is_valid():
# free split normal
self.__mAssocMesh.free_normals_split()
# free variable
self.__mAssocMesh = None
def get_face_count(self) -> int:
if not self.is_valid():
raise UTIL_functions.BBPException('try to call an invalid MeshUVModifier.')
return len(self.__mAssocMesh.polygons)
def get_face(self) -> typing.Iterator[FaceForModifyingUV]:
if not self.is_valid():
raise UTIL_functions.BBPException('try to call an invalid MeshUVModifier.')
cache: FaceForModifyingUV = FaceForModifyingUV(self.__mAssocMesh)
for poly in self.__mAssocMesh.polygons:
cache._set_face(poly)
yield cache

View File

@ -0,0 +1,7 @@
import bpy
import os, enum
class BlenderPresetIcons(enum.Enum):
Info = 'INFO'
Warning = 'ERROR'
Error = 'CANCEL'

View File

@ -25,7 +25,7 @@ if "bpy" in locals():
from . import PROP_preferences, PROP_virtools_material
from . import OP_IMPORT_bmfile, OP_EXPORT_bmfile, OP_IMPORT_virtools, OP_EXPORT_virtools
from . import OP_UV_flatten_uv
from . import OP_UV_flatten_uv, OP_UV_rail_uv
#region Menu
@ -38,8 +38,8 @@ class BBP_MT_View3DMenu(bpy.types.Menu):
def draw(self, context):
layout = self.layout
layout.operator(OP_UV_flatten_uv.BBP_OT_flatten_uv.bl_idname)
layout.operator(OP_UV_rail_uv.BBP_OT_rail_uv.bl_idname)
# ===== Menu Drawer =====
@ -92,6 +92,7 @@ def register() -> None:
OP_IMPORT_virtools.register()
OP_EXPORT_virtools.register()
OP_UV_rail_uv.register()
OP_UV_flatten_uv.register()
# register other classes
@ -116,6 +117,7 @@ def unregister() -> None:
# unregister modules
OP_UV_flatten_uv.unregister()
OP_UV_rail_uv.unregister()
OP_EXPORT_virtools.unregister()
OP_IMPORT_virtools.unregister()