Publish verified live restoration source snapshot and known limits
This commit is contained in:
@@ -1,53 +1,92 @@
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using NAudio.Lame;
|
||||
using UmaMusumeAudio;
|
||||
using NAudio.Wave.SampleProviders;
|
||||
using NAudio.Wave;
|
||||
|
||||
using UnityEngine;
|
||||
/// <summary>
|
||||
/// 使用多线程,防止导出音频时使用主线程导致UI卡死
|
||||
/// </summary>
|
||||
public class AudioExporter
|
||||
{
|
||||
public static IEnumerator ExportAudio(List<UmaWaveStream> a, string path, int index = -1) {
|
||||
|
||||
var l = new List<ISampleProvider>();
|
||||
if (index == -1)
|
||||
public static IEnumerator ExportAudio(List<UmaWaveStream> audioStreams, string path, int index = -1)
|
||||
{
|
||||
if (audioStreams == null || audioStreams.Count == 0)
|
||||
{
|
||||
foreach (var z in a)
|
||||
{
|
||||
l.Add(GetSampleFixedLength(z));
|
||||
}
|
||||
} else
|
||||
{
|
||||
l.Add(GetSampleFixedLength(a[index]));
|
||||
UmaViewerUI.Instance.ShowMessage("No audio available to export", UIMessageType.Warning);
|
||||
yield break;
|
||||
}
|
||||
|
||||
var wf = a[0].WaveFormat;
|
||||
if (index < -1 || index >= audioStreams.Count)
|
||||
{
|
||||
UmaViewerUI.Instance.ShowMessage("The selected audio track is no longer available", UIMessageType.Error);
|
||||
yield break;
|
||||
}
|
||||
|
||||
var mixer = new MixingSampleProvider(l);
|
||||
// 在 Unity 主线程中复制选中的内容
|
||||
// 在解码、混音、编码以及写入 MP3 文件的整个过程中,工作线程(worker)独占并管理这个列表
|
||||
var selectedStreams = index == -1
|
||||
? new List<UmaWaveStream>(audioStreams)
|
||||
: new List<UmaWaveStream> { audioStreams[index] };
|
||||
|
||||
Task exportTask = Task.Run(() => ExportAudioBlocking(selectedStreams, path));
|
||||
|
||||
// 协程依然运行在 Unity 主线程中,不过现在它只负责等待后台工作线程完成任务
|
||||
// 真正耗时的导出工作已经交给工作线程执行
|
||||
while (!exportTask.IsCompleted)
|
||||
{
|
||||
yield return null;
|
||||
}
|
||||
|
||||
if (exportTask.IsFaulted)
|
||||
{
|
||||
Exception exception = exportTask.Exception?.GetBaseException();
|
||||
if (exception != null)
|
||||
{
|
||||
Debug.LogException(exception);
|
||||
}
|
||||
|
||||
UmaViewerUI.Instance.ShowMessage(
|
||||
$"Audio export failed: {exception?.Message ?? "Unknown error"}",
|
||||
UIMessageType.Error);
|
||||
yield break;
|
||||
}
|
||||
|
||||
if (exportTask.IsCanceled)
|
||||
{
|
||||
UmaViewerUI.Instance.ShowMessage("Audio export was canceled", UIMessageType.Warning);
|
||||
yield break;
|
||||
}
|
||||
|
||||
UmaViewerUI.Instance.ShowMessage("Export complete", UIMessageType.Default);
|
||||
}
|
||||
|
||||
private static void ExportAudioBlocking(List<UmaWaveStream> audioStreams, string path)
|
||||
{
|
||||
var sampleProviders = new List<ISampleProvider>(audioStreams.Count);
|
||||
|
||||
foreach (var stream in audioStreams)
|
||||
{
|
||||
sampleProviders.Add(GetSampleFixedLength(stream));
|
||||
}
|
||||
|
||||
var waveFormat = audioStreams[0].WaveFormat;
|
||||
|
||||
var mixer = new MixingSampleProvider(sampleProviders);
|
||||
IWaveProvider sourceProvider = new SampleToWaveProvider16(mixer);
|
||||
|
||||
|
||||
using (var writer = new LameMP3FileWriter(path, new NAudio.Wave.WZT.WaveFormat(wf.SampleRate, wf.Channels), 320))
|
||||
using (var writer = new LameMP3FileWriter(path, new NAudio.Wave.WZT.WaveFormat(waveFormat.SampleRate, waveFormat.Channels), 320))
|
||||
{
|
||||
byte[] buffer = new byte[wf.AverageBytesPerSecond]; // Read about 1 second of audio at a time
|
||||
byte[] buffer = new byte[waveFormat.AverageBytesPerSecond];
|
||||
int bytesRead;
|
||||
|
||||
// Loop to read from the source IWaveProvider and write to the MP3 writer
|
||||
// The Read method returns 0 when there's no more data
|
||||
int safeguard = 0;
|
||||
while ((bytesRead = sourceProvider.Read(buffer, 0, buffer.Length)) > 0)
|
||||
{
|
||||
writer.Write(buffer, 0, bytesRead);
|
||||
if(++safeguard % 100 == 0)
|
||||
{
|
||||
if(safeguard % 500 == 0)
|
||||
{
|
||||
UmaViewerUI.Instance.ShowMessage("Possible loop detected! Close UmaViewer if this message continues appearing", UIMessageType.Warning);
|
||||
}
|
||||
yield return 0;
|
||||
}
|
||||
}
|
||||
UmaViewerUI.Instance.ShowMessage("Export complete", UIMessageType.Default);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ public class BillboardBuilder : MonoBehaviour
|
||||
|
||||
|
||||
|
||||
//修改(Billboard的导出相关)
|
||||
// 修改(Billboard 的顶点处理)
|
||||
public static Mesh CreateSphereMesh(float radius, int subdiv, float uvRadius, Vector2 uvCenter)
|
||||
{
|
||||
var t = (1f + Mathf.Sqrt(5f)) / 2f;
|
||||
@@ -150,7 +150,7 @@ public class BillboardBuilder : MonoBehaviour
|
||||
|
||||
|
||||
|
||||
//修改(Billboard的导出相关)
|
||||
//��(Billboard�ĵ������)
|
||||
if (radius < 0.003)
|
||||
{
|
||||
sphereMesh = CreateSphereMesh(radius, 1, uv_radius, uv_center);
|
||||
@@ -205,7 +205,7 @@ public class BillboardBuilder : MonoBehaviour
|
||||
|
||||
|
||||
|
||||
//修改(Billboard的导出相关)
|
||||
//��(Billboard�ĵ������)
|
||||
//ApplyBillboardUVOffset(s);
|
||||
|
||||
|
||||
@@ -230,7 +230,7 @@ public class BillboardBuilder : MonoBehaviour
|
||||
|
||||
|
||||
|
||||
//修改(Billboard的导出相关)
|
||||
//��(Billboard�ĵ������)
|
||||
private static void ApplyBillboardUVOffset(SkinnedMeshRenderer smr)
|
||||
{
|
||||
var mesh = smr.sharedMesh;
|
||||
|
||||
@@ -9,6 +9,7 @@ using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Rendering;
|
||||
using Gallop.Live.Cutt; // For FacialMouthId
|
||||
using static BillboardBuilder;
|
||||
using static LibMMD.Model.Morph;
|
||||
using static LibMMD.Model.SkinningOperator;
|
||||
@@ -19,30 +20,54 @@ public class ModelExporter
|
||||
{
|
||||
static string modelInfo = $"Generated by UmaViewer {Application.version}, Copyright Cygames \nLink : https://github.com/katboi01/UmaViewer";
|
||||
|
||||
// 仅过滤浮点烘焙产生的近零噪声;平方阈值 1e-12 对应实际位移 1e-6。
|
||||
private const float MorphVertexNoiseSqrThreshold = 0.000000000001f;
|
||||
private const int VmdMorphNameMaxShiftJisBytes = 15;
|
||||
|
||||
// 标准 MMD 表情按部位收集,最终烘焙为 Blender、MMD 与 MMDSkin 均可见的 Vertex Morph。
|
||||
private enum MorphPart
|
||||
{
|
||||
Eyebrow,
|
||||
Eye,
|
||||
Mouth
|
||||
}
|
||||
|
||||
public static void ExportModel(UmaContainerCharacter container, string path)
|
||||
{
|
||||
container.SetDynamicBoneEnable(false);
|
||||
container.EnablePhysics = false;
|
||||
container.UmaFaceAnimator?.Rebind();
|
||||
container.UmaAnimator?.Rebind();
|
||||
container.EnableEyeTracking = false;
|
||||
container.FaceDrivenKeyTarget?.FacialResetAll();
|
||||
AddBlendShape(container);
|
||||
BuildBillboard(container);
|
||||
PMXExportStateSnapshot stateSnapshot = new PMXExportStateSnapshot(container);
|
||||
try
|
||||
{
|
||||
stateSnapshot.FreezeForExport();
|
||||
// PMX 与 VMD 共用同一套 MMD 默认 A-pose,避免导出当前动画帧或近似 T-pose。
|
||||
stateSnapshot.ApplyMmdReferencePose();
|
||||
container.FaceDrivenKeyTarget?.FacialResetAll();
|
||||
AddBlendShape(container);
|
||||
BuildBillboard(container);
|
||||
|
||||
var textures = TextureExporter.ExportAllTexture(Path.GetDirectoryName(path), container.gameObject);
|
||||
var model = ReadPMXModel(container, textures, container.CharaEntry);
|
||||
var textures = TextureExporter.ExportAllTexture(Path.GetDirectoryName(path), container.gameObject);
|
||||
var model = ReadPMXModel(container, textures, container.CharaEntry);
|
||||
|
||||
FileStream fileStream = new FileStream(path, FileMode.Create);
|
||||
BinaryWriter writer = new BinaryWriter(fileStream);
|
||||
var config = new ModelConfig() { GlobalToonPath = "Toon" };
|
||||
PMXWriter.Write(writer, model, config);
|
||||
using (FileStream fileStream = new FileStream(path, FileMode.Create))
|
||||
using (BinaryWriter writer = new BinaryWriter(fileStream))
|
||||
{
|
||||
var config = new ModelConfig() { GlobalToonPath = "Toon" };
|
||||
PMXWriter.Write(writer, model, config);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
RemoveBillboard(container);
|
||||
ClearBlendShape(container);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// 临时导出资源清理失败时,也必须恢复角色的姿势和运行时组件。
|
||||
stateSnapshot.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
writer.Close();
|
||||
fileStream.Close();
|
||||
|
||||
RemoveBillboard(container);
|
||||
ClearBlendShape(container);
|
||||
UmaViewerUI.Instance.ShowMessage($"PMX Save at {path}", UIMessageType.Success);
|
||||
}
|
||||
|
||||
@@ -79,19 +104,29 @@ public class ModelExporter
|
||||
model.Description = model.DescriptionEn = $"{container.gameObject.name}\n{modelInfo}";
|
||||
}
|
||||
|
||||
//Rean Bones
|
||||
// 仅从蒙皮引用收集骨骼,避免把 Handle、Pole、Target 等运行时控制节点导出为 PMX 骨骼。
|
||||
var rootBone = container.transform.Find("Position");
|
||||
if (rootBone == null)
|
||||
{
|
||||
rootBone = container.transform;
|
||||
}
|
||||
List<Transform> bones = new List<Transform>(rootBone.GetComponentsInChildren<Transform>());
|
||||
bones.RemoveAll(o => o.name.Contains("Col_"));
|
||||
List<Renderer> renderers = new List<Renderer>(container.GetComponentsInChildren<Renderer>());
|
||||
// Geometry, materials and morphs must consume the same mesh-only renderer sequence.
|
||||
renderers.RemoveAll(renderer => !(renderer is MeshRenderer) && !(renderer is SkinnedMeshRenderer));
|
||||
PMXPhysicsExporter.Context physicsContext = null;
|
||||
if (container is UmaContainerCharacter physicsCharacter)
|
||||
{
|
||||
physicsContext = PMXPhysicsExporter.Prepare(physicsCharacter, rootBone);
|
||||
}
|
||||
PMXBoneExporter.Result boneResult = PMXBoneExporter.Build(
|
||||
rootBone,
|
||||
container.transform,
|
||||
renderers,
|
||||
physicsContext != null ? physicsContext.DynamicBones : null);
|
||||
|
||||
//Read vertices And triangles
|
||||
List<Renderer> renderers = new List<Renderer>(container.GetComponentsInChildren<Renderer>());
|
||||
List<int> triangles = new List<int>();
|
||||
model.Vertices = ReadVerticesAndTriangles(renderers, bones, ref triangles, container.transform);
|
||||
model.Vertices = ReadVerticesAndTriangles(renderers, boneResult.BoneIndexes, ref triangles, container.transform);
|
||||
model.TriangleIndexes = triangles.ToArray();
|
||||
|
||||
//Read Texture reference
|
||||
@@ -101,10 +136,22 @@ public class ModelExporter
|
||||
}
|
||||
|
||||
model.Parts = ReadPartMaterials(renderers, model);
|
||||
model.Bones = ReadBones(bones);
|
||||
model.Bones = boneResult.Bones;
|
||||
if(container is UmaContainerCharacter chara)
|
||||
{
|
||||
ClearBlendShape(chara);
|
||||
AddBlendShape(chara);
|
||||
}
|
||||
model.Morphs = ReadMorph(renderers);
|
||||
model.Rigidbodies = new MMDRigidBody[0];
|
||||
model.Joints = new MMDJoint[0];
|
||||
if (physicsContext != null)
|
||||
{
|
||||
PMXPhysicsExporter.Build(physicsContext, container.transform, boneResult, model);
|
||||
}
|
||||
else
|
||||
{
|
||||
model.Rigidbodies = new MMDRigidBody[0];
|
||||
model.Joints = new MMDJoint[0];
|
||||
}
|
||||
|
||||
return model;
|
||||
}
|
||||
@@ -135,29 +182,48 @@ public class ModelExporter
|
||||
SkinnedMeshRenderer faceMesh = null;
|
||||
SkinnedMeshRenderer eyebrowMesh = null;
|
||||
SkinnedMeshRenderer earMesh = null;
|
||||
SkinnedMeshRenderer mouthMesh = null; // New
|
||||
SkinnedMeshRenderer eyeMesh = null; // New
|
||||
|
||||
foreach (SkinnedMeshRenderer s in container.GetComponentsInChildren<SkinnedMeshRenderer>())
|
||||
{
|
||||
if (s.name.Equals("M_Face")) faceMesh = s;
|
||||
else if (s.name.Equals("M_Mayu")) eyebrowMesh = s;
|
||||
else if (s.name.Equals("M_Hair")) earMesh = s;
|
||||
else if (s.name.Equals("M_Mouth")) mouthMesh = s; // New
|
||||
else if (s.name.Equals("M_Eye")) eyeMesh = s; // New
|
||||
}
|
||||
|
||||
var facial = container.FaceDrivenKeyTarget;
|
||||
Action<SkinnedMeshRenderer, List<FacialMorph>, Mesh> addBlendShapePart = delegate (SkinnedMeshRenderer skin, List<FacialMorph> morphs, Mesh baseMesh)
|
||||
{
|
||||
container.FaceOverrideData = null;
|
||||
HashSet<string> usedNames = new HashSet<string>(StringComparer.Ordinal);
|
||||
for (int blendShapeIndex = 0; blendShapeIndex < skin.sharedMesh.blendShapeCount; blendShapeIndex++)
|
||||
{
|
||||
usedNames.Add(skin.sharedMesh.GetBlendShapeName(blendShapeIndex));
|
||||
}
|
||||
|
||||
foreach (var morph in morphs)
|
||||
{
|
||||
facial.ClearAllWeights();
|
||||
morph.weight = 1;
|
||||
// [Fix] Reset weight to 1 (User request: 10x was too strong)
|
||||
morph.weight = 1;
|
||||
facial.ChangeMorph();
|
||||
|
||||
Mesh deltaMesh = new Mesh();
|
||||
skin.BakeMesh(deltaMesh);
|
||||
skin.sharedMesh.AddBlendShapeFrame( $"{morph.name}({morph.tag})[{skin.name}]", 1,
|
||||
CalDelta(baseMesh.vertices, deltaMesh.vertices),
|
||||
CalDelta(baseMesh.normals, deltaMesh.normals),
|
||||
CalDelta(Vec4ToVec3(baseMesh.tangents), Vec4ToVec3(deltaMesh.tangents)));
|
||||
|
||||
// VMD 名称限制为 Shift-JIS 15 字节;冲突时追加稳定数字后缀,不能静默丢表情。
|
||||
string validName = MakeUniqueShiftJisName(morph.name, usedNames, VmdMorphNameMaxShiftJisBytes);
|
||||
usedNames.Add(validName);
|
||||
|
||||
// [Fix] Use weight 100.0f (Standard Unity Full Weight)
|
||||
// Previous value 1.0f meant "This delta is for 1% weight", causing MMD (100%) to explode the mesh 100x.
|
||||
skin.sharedMesh.AddBlendShapeFrame(validName, 100.0f,
|
||||
CalDelta(baseMesh.vertices, deltaMesh.vertices),
|
||||
CalDelta(baseMesh.normals, deltaMesh.normals),
|
||||
CalDelta(Vec4ToVec3(baseMesh.tangents), Vec4ToVec3(deltaMesh.tangents)));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -183,6 +249,22 @@ public class ModelExporter
|
||||
earMesh.BakeMesh(baseEarMesh);
|
||||
addBlendShapePart(earMesh, facial.EarMorphs, baseEarMesh);
|
||||
}
|
||||
|
||||
// [New] Process Mouth Mesh
|
||||
if (mouthMesh)
|
||||
{
|
||||
Mesh baseMouthMesh = new Mesh();
|
||||
mouthMesh.BakeMesh(baseMouthMesh);
|
||||
addBlendShapePart(mouthMesh, facial.MouthMorphs, baseMouthMesh);
|
||||
}
|
||||
|
||||
// [New] Process Eye Mesh
|
||||
if (eyeMesh)
|
||||
{
|
||||
Mesh baseEyeMesh = new Mesh();
|
||||
eyeMesh.BakeMesh(baseEyeMesh);
|
||||
addBlendShapePart(eyeMesh, facial.EyeMorphs, baseEyeMesh);
|
||||
}
|
||||
|
||||
facial.ClearAllWeights();
|
||||
facial.ChangeMorph();
|
||||
@@ -194,17 +276,53 @@ public class ModelExporter
|
||||
//assuming base meshes do not have any blend shapes
|
||||
foreach (SkinnedMeshRenderer s in container.GetComponentsInChildren<SkinnedMeshRenderer>())
|
||||
{
|
||||
if (s.name.Equals("M_Face") || s.name.Equals("M_Mayu") || s.name.Equals("M_Hair"))
|
||||
if (s.name.Equals("M_Face") || s.name.Equals("M_Mayu") || s.name.Equals("M_Hair") ||
|
||||
s.name.Equals("M_Mouth") || s.name.Equals("M_Eye"))
|
||||
{
|
||||
s.sharedMesh.ClearBlendShapes();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string TruncateToShiftJIS(string s, int maxBytes)
|
||||
{
|
||||
var encoding = System.Text.Encoding.GetEncoding("shift_jis");
|
||||
if (encoding.GetByteCount(s) <= maxBytes) return s;
|
||||
|
||||
// 按字符逐个累计字节,避免直接截断 Shift-JIS 双字节字符产生乱码。
|
||||
int charCount = 0;
|
||||
int byteCount = 0;
|
||||
while (charCount < s.Length)
|
||||
{
|
||||
int currentBytes = encoding.GetByteCount(s.Substring(charCount, 1));
|
||||
if (byteCount + currentBytes > maxBytes) break;
|
||||
byteCount += currentBytes;
|
||||
charCount++;
|
||||
}
|
||||
return s.Substring(0, charCount);
|
||||
}
|
||||
|
||||
private static string MakeUniqueShiftJisName(string sourceName, HashSet<string> usedNames, int maxBytes)
|
||||
{
|
||||
string candidate = TruncateToShiftJIS(sourceName, maxBytes);
|
||||
if (!usedNames.Contains(candidate)) return candidate;
|
||||
|
||||
// 从 2 开始表示同一截断名的第 2 项;后缀始终计入 15 字节限制。
|
||||
for (int duplicateIndex = 2; ; duplicateIndex++)
|
||||
{
|
||||
string suffix = "_" + duplicateIndex;
|
||||
int prefixBytes = maxBytes - System.Text.Encoding.GetEncoding("shift_jis").GetByteCount(suffix);
|
||||
candidate = TruncateToShiftJIS(sourceName, System.Math.Max(0, prefixBytes)) + suffix;
|
||||
if (!usedNames.Contains(candidate)) return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
private static Morph[] ReadMorph(List<Renderer> renderers)
|
||||
{
|
||||
List<Morph> morphs = new List<Morph>();
|
||||
Dictionary<string, List<VertexMorphData>> mergedMorphData = new Dictionary<string, List<VertexMorphData>>();
|
||||
List<string> rawMorphOrder = new List<string>();
|
||||
int vertexOffset = 0;
|
||||
|
||||
foreach (Renderer renderer in renderers)
|
||||
{
|
||||
Mesh mesh;
|
||||
@@ -219,75 +337,326 @@ public class ModelExporter
|
||||
}
|
||||
var vertexCount = mesh.vertexCount;
|
||||
|
||||
for (int i = 0; i < mesh.blendShapeCount; i++)
|
||||
for (int i = 0; i < mesh.blendShapeCount; i++)
|
||||
{
|
||||
string morphName = mesh.GetBlendShapeName(i);
|
||||
int frameCount = mesh.GetBlendShapeFrameCount(i);
|
||||
if (frameCount <= 0)
|
||||
{
|
||||
// 没有任何有效帧时无法取得顶点偏移,直接跳过该 BlendShape。
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!mergedMorphData.ContainsKey(morphName))
|
||||
{
|
||||
mergedMorphData[morphName] = new List<VertexMorphData>();
|
||||
rawMorphOrder.Add(morphName);
|
||||
}
|
||||
|
||||
var deltaVertices = new Vector3[vertexCount];
|
||||
var deltaNormals = new Vector3[vertexCount];
|
||||
var deltaTangents= new Vector3[vertexCount];
|
||||
mesh.GetBlendShapeFrameVertices(i, 0, deltaVertices, deltaNormals, deltaTangents);
|
||||
var deltaTangents = new Vector3[vertexCount];
|
||||
// Unity BlendShape 可能含多个权重帧,导出最终有效帧而不是固定读取第 0 帧。
|
||||
mesh.GetBlendShapeFrameVertices(i, frameCount - 1, deltaVertices, deltaNormals, deltaTangents);
|
||||
|
||||
Morph morph = new Morph();
|
||||
morph.Name = morph.NameEn = mesh.GetBlendShapeName(i);
|
||||
morph.Type = MorphType.MorphTypeVertex;
|
||||
var datas = new VertexMorphData[vertexCount];
|
||||
for (int j = 0; j < vertexCount; j++)
|
||||
for (int j = 0; j < vertexCount; j++)
|
||||
{
|
||||
var data = new VertexMorphData();
|
||||
data.VertexIndex = vertexOffset + j;
|
||||
data.Offset = deltaVertices[j];
|
||||
datas[j] = data;
|
||||
// 只剔除真正零位移/数值噪声,保留脸部的细微顶点变化。
|
||||
if (deltaVertices[j].sqrMagnitude > MorphVertexNoiseSqrThreshold)
|
||||
{
|
||||
var data = new VertexMorphData();
|
||||
data.VertexIndex = vertexOffset + j;
|
||||
data.Offset = deltaVertices[j];
|
||||
mergedMorphData[morphName].Add(data);
|
||||
}
|
||||
}
|
||||
morph.MorphDatas = datas;
|
||||
}
|
||||
vertexOffset += vertexCount;
|
||||
}
|
||||
|
||||
if (morph.Name.Contains("Mouth_"))
|
||||
{
|
||||
morph.Category = MorphCategory.MorphCatMouth;
|
||||
}
|
||||
else if(morph.Name.Contains("EyeBrow_"))
|
||||
{
|
||||
morph.Category = MorphCategory.MorphCatEyebrow;
|
||||
}
|
||||
else if(morph.Name.Contains("Eye_"))
|
||||
{
|
||||
morph.Category = MorphCategory.MorphCatEye;
|
||||
}
|
||||
else
|
||||
{
|
||||
morph.Category = MorphCategory.MorphCatOther;
|
||||
}
|
||||
List<Morph> finalMorphs = new List<Morph>();
|
||||
HashSet<string> usedMorphNames = new HashSet<string>(StringComparer.Ordinal);
|
||||
Dictionary<string, Dictionary<MorphPart, List<VertexMorphData>>> mappedMorphData =
|
||||
new Dictionary<string, Dictionary<MorphPart, List<VertexMorphData>>>(StringComparer.Ordinal);
|
||||
List<string> mappedMorphOrder = new List<string>();
|
||||
|
||||
morphs.Add(morph);
|
||||
// 标准入口名必须保持精确,先预留名称;原始 Morph 若同名则使用稳定数字后缀。
|
||||
HashSet<string> reservedStandardNames = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (string rawName in rawMorphOrder)
|
||||
{
|
||||
if (mergedMorphData[rawName].Count == 0) continue;
|
||||
string mappedName = GetMappedMMDName(rawName);
|
||||
if (!string.IsNullOrEmpty(mappedName)) reservedStandardNames.Add(mappedName);
|
||||
}
|
||||
|
||||
foreach (string rawName in rawMorphOrder)
|
||||
{
|
||||
List<VertexMorphData> rawData = mergedMorphData[rawName];
|
||||
// 空 Morph 不包含任何有效顶点,既不导出原始项,也不参与标准表情组合。
|
||||
if (rawData.Count == 0) continue;
|
||||
|
||||
string uniqueRawName = MakeUniqueMorphName(rawName, usedMorphNames, reservedStandardNames);
|
||||
MorphPart rawPart = GetMorphPart(rawName);
|
||||
finalMorphs.Add(CreateVertexMorph(uniqueRawName, rawName, rawData, GetOriginalMorphCategory(rawName)));
|
||||
usedMorphNames.Add(uniqueRawName);
|
||||
|
||||
// 将左右同部位顶点合并,但不再跨眉、眼、口直接拼成同一个 Vertex Morph。
|
||||
string mmdName = GetMappedMMDName(rawName);
|
||||
if (!string.IsNullOrEmpty(mmdName))
|
||||
{
|
||||
if (!mappedMorphData.ContainsKey(mmdName))
|
||||
{
|
||||
mappedMorphData[mmdName] = new Dictionary<MorphPart, List<VertexMorphData>>();
|
||||
mappedMorphOrder.Add(mmdName);
|
||||
}
|
||||
if (!mappedMorphData[mmdName].ContainsKey(rawPart))
|
||||
{
|
||||
mappedMorphData[mmdName][rawPart] = new List<VertexMorphData>();
|
||||
}
|
||||
mappedMorphData[mmdName][rawPart].AddRange(rawData);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (string mmdName in mappedMorphOrder)
|
||||
{
|
||||
Dictionary<MorphPart, List<VertexMorphData>> partData = mappedMorphData[mmdName];
|
||||
List<VertexMorphData> bakedData = new List<VertexMorphData>();
|
||||
foreach (MorphPart part in new MorphPart[] { MorphPart.Eyebrow, MorphPart.Eye, MorphPart.Mouth })
|
||||
{
|
||||
if (!partData.ContainsKey(part)) continue;
|
||||
bakedData.AddRange(partData[part]);
|
||||
|
||||
// 多部位组合仍保留可单独调整的部位副本,但标准入口不再使用 Group Morph。
|
||||
if (partData.Count > 1)
|
||||
{
|
||||
string partName = MakeUniqueMorphName(mmdName + GetMorphPartSuffix(part), usedMorphNames, reservedStandardNames);
|
||||
finalMorphs.Add(CreateVertexMorph(partName, partName, MergeVertexMorphData(partData[part]), GetMorphCategory(part)));
|
||||
usedMorphNames.Add(partName);
|
||||
}
|
||||
}
|
||||
|
||||
vertexOffset += mesh.vertexCount;
|
||||
// 同一顶点可能同时受多个源表情影响,按顶点索引求和后烘焙为一个标准 Vertex Morph。
|
||||
MorphPart standardPart = GetStandardMorphPart(partData);
|
||||
finalMorphs.Add(CreateVertexMorph(mmdName, mmdName, MergeVertexMorphData(bakedData), GetMorphCategory(standardPart)));
|
||||
usedMorphNames.Add(mmdName);
|
||||
}
|
||||
return morphs.ToArray();
|
||||
|
||||
return finalMorphs.ToArray();
|
||||
}
|
||||
|
||||
private static Bone[] ReadBones(List<Transform> bonelist)
|
||||
private static Morph CreateVertexMorph(string name, string nameEn, List<VertexMorphData> datas, MorphCategory category)
|
||||
{
|
||||
List<Bone> pmxbones = new List<Bone>();
|
||||
foreach (var bone in bonelist)
|
||||
{
|
||||
Bone pmxbone = new Bone();
|
||||
pmxbone.Name = pmxbone.NameEn = bone.name;
|
||||
pmxbone.Position = bone.position;
|
||||
pmxbone.ParentIndex = bonelist.IndexOf(bone.parent);
|
||||
pmxbone.TransformLevel = 0;
|
||||
pmxbone.Visible = true;
|
||||
pmxbone.Movable = true;
|
||||
pmxbone.Rotatable = true;
|
||||
pmxbone.Controllable = true;
|
||||
pmxbone.ChildBoneVal = new Bone.ChildBone()
|
||||
{
|
||||
ChildUseId = true,
|
||||
Index = (bone.childCount > 0 ? bonelist.IndexOf(bone.GetChild(0)) : -1)
|
||||
};
|
||||
pmxbones.Add(pmxbone);
|
||||
}
|
||||
return pmxbones.ToArray();
|
||||
Morph morph = new Morph();
|
||||
morph.Name = name;
|
||||
morph.NameEn = nameEn;
|
||||
morph.Type = MorphType.MorphTypeVertex;
|
||||
morph.MorphDatas = datas.ToArray();
|
||||
morph.Category = category;
|
||||
return morph;
|
||||
}
|
||||
|
||||
private static List<VertexMorphData> MergeVertexMorphData(IEnumerable<VertexMorphData> source)
|
||||
{
|
||||
Dictionary<int, Vector3> offsetsByVertex = new Dictionary<int, Vector3>();
|
||||
foreach (VertexMorphData data in source)
|
||||
{
|
||||
if (offsetsByVertex.TryGetValue(data.VertexIndex, out Vector3 currentOffset))
|
||||
{
|
||||
offsetsByVertex[data.VertexIndex] = currentOffset + data.Offset;
|
||||
}
|
||||
else
|
||||
{
|
||||
offsetsByVertex[data.VertexIndex] = data.Offset;
|
||||
}
|
||||
}
|
||||
|
||||
List<int> sortedVertexIndices = new List<int>(offsetsByVertex.Keys);
|
||||
sortedVertexIndices.Sort();
|
||||
List<VertexMorphData> merged = new List<VertexMorphData>(offsetsByVertex.Count);
|
||||
foreach (int vertexIndex in sortedVertexIndices)
|
||||
{
|
||||
Vector3 offset = offsetsByVertex[vertexIndex];
|
||||
// 多源相加后若恰好抵消为零,则无需写入 PMX。
|
||||
if (offset.sqrMagnitude <= MorphVertexNoiseSqrThreshold) continue;
|
||||
merged.Add(new VertexMorphData { VertexIndex = vertexIndex, Offset = offset });
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
private static MorphPart GetStandardMorphPart(Dictionary<MorphPart, List<VertexMorphData>> partData)
|
||||
{
|
||||
// 标准名正常只属于一个 MMD 分类;兼容旧组合时按眉、眼、口优先级选择面板分类。
|
||||
if (partData.ContainsKey(MorphPart.Eyebrow)) return MorphPart.Eyebrow;
|
||||
if (partData.ContainsKey(MorphPart.Eye)) return MorphPart.Eye;
|
||||
return MorphPart.Mouth;
|
||||
}
|
||||
|
||||
private static MorphPart GetMorphPart(string rawName)
|
||||
{
|
||||
if (rawName.StartsWith("EyeBrow_", StringComparison.Ordinal) || rawName.Contains("眉"))
|
||||
{
|
||||
return MorphPart.Eyebrow;
|
||||
}
|
||||
if (rawName.StartsWith("Mouth_", StringComparison.Ordinal) || rawName.Contains("口") || rawName.Contains("Lip"))
|
||||
{
|
||||
return MorphPart.Mouth;
|
||||
}
|
||||
return MorphPart.Eye;
|
||||
}
|
||||
|
||||
private static MorphCategory GetOriginalMorphCategory(string rawName)
|
||||
{
|
||||
// 原始 Morph 保持原有的按名称分类;耳部等非眉眼口项目归入 Other。
|
||||
if (rawName.Contains("Mouth") || rawName.Contains("口") || rawName.Contains("Lip"))
|
||||
{
|
||||
return MorphCategory.MorphCatMouth;
|
||||
}
|
||||
if (rawName.Contains("EyeBrow") || rawName.Contains("眉"))
|
||||
{
|
||||
return MorphCategory.MorphCatEyebrow;
|
||||
}
|
||||
if (rawName.Contains("Eye") || rawName.Contains("目") || rawName.Contains("まばたき"))
|
||||
{
|
||||
return MorphCategory.MorphCatEye;
|
||||
}
|
||||
return MorphCategory.MorphCatOther;
|
||||
}
|
||||
|
||||
private static MorphCategory GetMorphCategory(MorphPart part)
|
||||
{
|
||||
if (part == MorphPart.Eyebrow) return MorphCategory.MorphCatEyebrow;
|
||||
if (part == MorphPart.Mouth) return MorphCategory.MorphCatMouth;
|
||||
return MorphCategory.MorphCatEye;
|
||||
}
|
||||
|
||||
private static string GetMorphPartSuffix(MorphPart part)
|
||||
{
|
||||
if (part == MorphPart.Eyebrow) return "_眉";
|
||||
if (part == MorphPart.Mouth) return "_口";
|
||||
return "_目";
|
||||
}
|
||||
|
||||
private static string MakeUniqueMorphName(string sourceName, HashSet<string> usedNames, HashSet<string> reservedNames)
|
||||
{
|
||||
if (!usedNames.Contains(sourceName) && !reservedNames.Contains(sourceName)) return sourceName;
|
||||
|
||||
// PMX 本身不受 VMD 15 字节限制;数字后缀保证结果稳定、可预测且全局唯一。
|
||||
for (int duplicateIndex = 2; ; duplicateIndex++)
|
||||
{
|
||||
string candidate = sourceName + "_" + duplicateIndex;
|
||||
if (!usedNames.Contains(candidate) && !reservedNames.Contains(candidate)) return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetMappedMMDName(string rawName)
|
||||
{
|
||||
// 1. Direct Mapping
|
||||
if (MorphNameMapping.TryGetValue(rawName, out string mapped)) return mapped;
|
||||
|
||||
// 2. Parse Unity Patterns (e.g. Eye_2_L -> Eye_CloseA -> まばたき)
|
||||
|
||||
// Eyes: Eye_{id}_{L/R}
|
||||
if (rawName.StartsWith("Eye_"))
|
||||
{
|
||||
var parts = rawName.Split('_');
|
||||
if (parts.Length >= 2 && int.TryParse(parts[1], out int id))
|
||||
{
|
||||
if (Enum.IsDefined(typeof(Gallop.Live.Cutt.LiveTimelineDefine.FacialEyeId), id))
|
||||
{
|
||||
string tag = Enum.GetName(typeof(Gallop.Live.Cutt.LiveTimelineDefine.FacialEyeId), id);
|
||||
string key = "Eye_" + tag; // e.g. "Eye_CloseA"
|
||||
// 左右 WaraiD 在正确参考模型中可精确对应传统 MMD 的左右 Wink。
|
||||
if (parts.Length >= 3 && tag == "WaraiD")
|
||||
{
|
||||
if (parts[2].StartsWith("L", StringComparison.Ordinal)) return "ウィンク";
|
||||
if (parts[2].StartsWith("R", StringComparison.Ordinal)) return "ウィンク右";
|
||||
}
|
||||
if (MorphNameMapping.TryGetValue(key, out string mmdName)) return mmdName;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Eyebrows: EyeBrow_{id}_{L/R}
|
||||
else if (rawName.StartsWith("EyeBrow_"))
|
||||
{
|
||||
var parts = rawName.Split('_');
|
||||
if (parts.Length >= 2 && int.TryParse(parts[1], out int id))
|
||||
{
|
||||
if (Enum.IsDefined(typeof(Gallop.Live.Cutt.LiveTimelineDefine.FacialEyebrowId), id))
|
||||
{
|
||||
string tag = Enum.GetName(typeof(Gallop.Live.Cutt.LiveTimelineDefine.FacialEyebrowId), id);
|
||||
string key = "EyeBrow_" + tag;
|
||||
if (MorphNameMapping.TryGetValue(key, out string mmdName)) return mmdName;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Mouth: Mouth_{id}_{index}
|
||||
else if (rawName.StartsWith("Mouth_"))
|
||||
{
|
||||
var parts = rawName.Split('_');
|
||||
if (parts.Length >= 2 && int.TryParse(parts[1], out int id))
|
||||
{
|
||||
if (Enum.IsDefined(typeof(Gallop.Live.Cutt.LiveTimelineDefine.FacialMouthId), id))
|
||||
{
|
||||
string tag = Enum.GetName(typeof(Gallop.Live.Cutt.LiveTimelineDefine.FacialMouthId), id);
|
||||
string key = "Mouth_" + tag; // e.g. "Mouth_WaraiA"
|
||||
|
||||
if (MorphNameMapping.TryGetValue(key, out string mmdName)) return mmdName;
|
||||
|
||||
// Fallback for Mouth which sometimes had "Mouth" prefix in mapping keys or direct names?
|
||||
// Existing mapping has keys like "Mouth_WaraiA". So "Mouth_" + tag is correct.
|
||||
|
||||
// Check for specialized suffix matches if needed, but for now tag matching is safer
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// UmaViewer Morph Name -> MMD 生态事实标准名称。
|
||||
// 仅映射有参考模型或通行惯例支撑的形态,避免生成“名称正确、形状错误”的空壳标准项。
|
||||
private static readonly Dictionary<string, string> MorphNameMapping = new Dictionary<string, string>()
|
||||
{
|
||||
// 眉
|
||||
{ "EyeBrow_SeriousA", "真面目" },
|
||||
{ "EyeBrow_WaraiD", "にこり" },
|
||||
{ "EyeBrow_IkariA", "怒り" },
|
||||
{ "EyeBrow_KanasiA", "悲しむ" },
|
||||
{ "EyeBrow_KomariA", "困る" },
|
||||
{ "EyeBrow_Offset_U", "上" },
|
||||
{ "EyeBrow_Offset_D", "下" },
|
||||
|
||||
// 眼
|
||||
{ "Eye_CloseA", "まばたき" }, // Blink
|
||||
{ "Eye_WaraiA", "笑い" }, // Smile
|
||||
{ "Eye_HalfA", "じと目" }, // Half-closed
|
||||
{ "Eye_OdorokiA", "びっくり" }, // Surprised
|
||||
// 参考模型顶点差异显示 KanasiA 比字面上的 IkariA 更接近传统“怒り目”。
|
||||
{ "Eye_KanasiA", "怒り目" },
|
||||
{ "Eye_PupilA", "瞳小" },
|
||||
|
||||
// 口 - 元音;大口型占用标准 VMD 名,小口型保留传统数字后缀。
|
||||
{ "Mouth_TalkA_A_L", "あ" },
|
||||
{ "Mouth_TalkA_I_L", "い" },
|
||||
{ "Mouth_TalkA_U_L", "う" },
|
||||
{ "Mouth_TalkA_E_L", "え" },
|
||||
{ "Mouth_TalkA_O_L", "お" },
|
||||
|
||||
{ "Mouth_TalkA_A_S", "あ2" }, // Smaller versions?
|
||||
{ "Mouth_TalkA_I_S", "い2" },
|
||||
{ "Mouth_TalkA_U_S", "う2" },
|
||||
{ "Mouth_TalkA_E_S", "え2" },
|
||||
{ "Mouth_TalkA_O_S", "お2" },
|
||||
|
||||
// 口 - 表情。不要再与眉/眼的标准名称跨部位合并。
|
||||
{ "Mouth_WaraiA", "にやり" },
|
||||
{ "Mouth_WaraiB", "にっこり" },
|
||||
{ "Mouth_IkariA", "怒り口" },
|
||||
{ "Mouth_KomariA", "困る口" },
|
||||
{ "Mouth_UreiA", "▲" }, // Triangle mouth?
|
||||
{ "Mouth_OdorokiA", "□" }, // Box mouth?
|
||||
};
|
||||
|
||||
private static Part[] ReadPartMaterials(List<Renderer> renderers, RawMMDModel model)
|
||||
{
|
||||
List<Part> parts = new List<Part>();
|
||||
@@ -305,11 +674,8 @@ public class ModelExporter
|
||||
{
|
||||
mesh = ((SkinnedMeshRenderer)renderer).sharedMesh;
|
||||
}
|
||||
if (!mesh.isReadable)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
var materials = new List<Material>(renderer.sharedMaterials);
|
||||
int rendererIndexCount = 0;
|
||||
for (int i = 0; i < mesh.subMeshCount; i++)
|
||||
{
|
||||
var material = (i < materials.Count ? materials[i] : materials[materials.Count - 1]);
|
||||
@@ -326,7 +692,7 @@ public class ModelExporter
|
||||
mat.DrawSelfShadow = true;
|
||||
mat.EdgeColor = Color.black;
|
||||
mat.EdgeSize = 0.4f;
|
||||
if (material.HasProperty("_MainTex"))
|
||||
if (material.HasProperty("_MainTex") && material.mainTexture != null)
|
||||
{
|
||||
var tex = model.TextureList.Find(t => t.TexturePath.Contains($"/{material.mainTexture.name}.png"));
|
||||
mat.Texture = (tex ?? model.TextureList[0]);
|
||||
@@ -336,16 +702,18 @@ public class ModelExporter
|
||||
mat.Texture = model.TextureList[0];
|
||||
}
|
||||
mat.MetaInfo = "";
|
||||
part.BaseShift = baseShift + mesh.GetSubMesh(i).indexStart;
|
||||
part.TriangleIndexNum = mesh.GetSubMesh(i).indexCount;
|
||||
var subMesh = mesh.GetSubMesh(i);
|
||||
part.BaseShift = baseShift + subMesh.indexStart;
|
||||
part.TriangleIndexNum = subMesh.indexCount;
|
||||
rendererIndexCount += subMesh.indexCount;
|
||||
parts.Add(part);
|
||||
}
|
||||
baseShift += mesh.triangles.Length;
|
||||
baseShift += rendererIndexCount;
|
||||
}
|
||||
return parts.ToArray();
|
||||
}
|
||||
|
||||
private static Vertex[] ReadVerticesAndTriangles(List<Renderer> renderers, List<Transform> bones, ref List<int> triangleList, Transform root)
|
||||
private static Vertex[] ReadVerticesAndTriangles(List<Renderer> renderers, Dictionary<Transform, int> boneIndexes, ref List<int> triangleList, Transform root)
|
||||
{
|
||||
List<Vertex> verticesList = new List<Vertex>();
|
||||
int vertexOffset = 0;
|
||||
@@ -364,10 +732,9 @@ public class ModelExporter
|
||||
{
|
||||
mesh = MakeReadableMeshCopy(mesh);
|
||||
}
|
||||
catch
|
||||
catch (Exception ex)
|
||||
{
|
||||
UmaViewerUI.Instance.ShowMessage($"Export {mesh.name} Failed : Mesh is not readable", UIMessageType.Error);
|
||||
continue;
|
||||
throw new InvalidOperationException($"Cannot export unreadable mesh {mesh.name} on {renderer.name}", ex);
|
||||
}
|
||||
}
|
||||
var vertices = mesh.vertices;
|
||||
@@ -393,7 +760,7 @@ public class ModelExporter
|
||||
};
|
||||
|
||||
vertex.SkinningOperator = new SkinningOperator() { Type = SkinningType.SkinningBdef1 };
|
||||
vertex.SkinningOperator.Param = new Bdef1() { BoneId = bones.IndexOf(renderer.transform) };
|
||||
vertex.SkinningOperator.Param = new Bdef1() { BoneId = GetBoneIndex(boneIndexes, renderer.transform) };
|
||||
vertex.EdgeScale = 1;
|
||||
verticesList.Add(vertex);
|
||||
}
|
||||
@@ -407,7 +774,8 @@ public class ModelExporter
|
||||
}
|
||||
else if (renderer is SkinnedMeshRenderer smr)
|
||||
{
|
||||
var mesh = smr.sharedMesh;
|
||||
var skinMesh = smr.sharedMesh;
|
||||
var mesh = skinMesh;
|
||||
if (!mesh.isReadable)
|
||||
{
|
||||
UmaViewerUI.Instance.ShowMessage($"Mesh {mesh.name} was not readable. Attempting to export", UIMessageType.Warning);
|
||||
@@ -415,10 +783,9 @@ public class ModelExporter
|
||||
{
|
||||
mesh = MakeReadableMeshCopy(mesh);
|
||||
}
|
||||
catch
|
||||
catch (Exception ex)
|
||||
{
|
||||
UmaViewerUI.Instance.ShowMessage($"Export {mesh.name} Failed : Mesh is not readable", UIMessageType.Error);
|
||||
continue;
|
||||
throw new InvalidOperationException($"Cannot export unreadable skinned mesh {mesh.name} on {renderer.name}", ex);
|
||||
}
|
||||
}
|
||||
var vertices = mesh.vertices;
|
||||
@@ -427,10 +794,11 @@ public class ModelExporter
|
||||
var uv1 = mesh.uv2;
|
||||
var uv2 = mesh.uv3;
|
||||
var colors = mesh.colors;
|
||||
var boneCounts = mesh.GetBonesPerVertex();
|
||||
// Geometry may need a GPU-readable copy, but that copy has no valid skinning data.
|
||||
var boneCounts = skinMesh.GetBonesPerVertex();
|
||||
var skinbone = smr.bones;
|
||||
var skinbones = smr.bones;
|
||||
var weights = mesh.boneWeights;
|
||||
var weights = skinMesh.boneWeights;
|
||||
var bakemesh = new Mesh();
|
||||
smr.BakeMesh(bakemesh,true);
|
||||
|
||||
@@ -454,13 +822,13 @@ public class ModelExporter
|
||||
{
|
||||
case 0:
|
||||
vertex.SkinningOperator = new SkinningOperator() { Type = SkinningType.SkinningBdef1 };
|
||||
vertex.SkinningOperator.Param = new Bdef1() { BoneId = GetBoneIndex(bones, renderer.transform) };
|
||||
vertex.SkinningOperator.Param = new Bdef1() { BoneId = GetBoneIndex(boneIndexes, renderer.transform) };
|
||||
break;
|
||||
|
||||
default:
|
||||
case 1:
|
||||
vertex.SkinningOperator = new SkinningOperator() { Type = SkinningType.SkinningBdef1 };
|
||||
vertex.SkinningOperator.Param = new Bdef1() { BoneId = GetBoneIndex(bones, skinbone[boneWeight.boneIndex0]) };
|
||||
vertex.SkinningOperator.Param = new Bdef1() { BoneId = GetBoneIndex(boneIndexes, skinbone[boneWeight.boneIndex0]) };
|
||||
break;
|
||||
|
||||
case 2:
|
||||
@@ -468,8 +836,8 @@ public class ModelExporter
|
||||
vertex.SkinningOperator.Param = new Bdef2()
|
||||
{
|
||||
BoneId = new int[]{
|
||||
GetBoneIndex(bones, skinbone[boneWeight.boneIndex0]),
|
||||
GetBoneIndex(bones, skinbone[boneWeight.boneIndex1]),
|
||||
GetBoneIndex(boneIndexes, skinbone[boneWeight.boneIndex0]),
|
||||
GetBoneIndex(boneIndexes, skinbone[boneWeight.boneIndex1]),
|
||||
},
|
||||
BoneWeight = boneWeight.weight0
|
||||
};
|
||||
@@ -481,10 +849,10 @@ public class ModelExporter
|
||||
vertex.SkinningOperator.Param = new Bdef4()
|
||||
{
|
||||
BoneId = new int[]{
|
||||
GetBoneIndex(bones, skinbone[boneWeight.boneIndex0]),
|
||||
GetBoneIndex(bones, skinbone[boneWeight.boneIndex1]),
|
||||
GetBoneIndex(bones, skinbone[boneWeight.boneIndex2]),
|
||||
GetBoneIndex(bones, skinbone[boneWeight.boneIndex3]),
|
||||
GetBoneIndex(boneIndexes, skinbone[boneWeight.boneIndex0]),
|
||||
GetBoneIndex(boneIndexes, skinbone[boneWeight.boneIndex1]),
|
||||
GetBoneIndex(boneIndexes, skinbone[boneWeight.boneIndex2]),
|
||||
GetBoneIndex(boneIndexes, skinbone[boneWeight.boneIndex3]),
|
||||
},
|
||||
BoneWeight = new float[]
|
||||
{
|
||||
@@ -510,9 +878,21 @@ public class ModelExporter
|
||||
return verticesList.ToArray();
|
||||
}
|
||||
|
||||
private static int GetBoneIndex(List<Transform> bones, Transform bone)
|
||||
private static int GetBoneIndex(Dictionary<Transform, int> boneIndexes, Transform bone)
|
||||
{
|
||||
return bones.Contains(bone) ? bones.IndexOf(bone) : 0;
|
||||
// 被过滤骨的权重转交给最近的有效祖先,保证索引始终指向实际 PMX 骨骼。
|
||||
Transform current = bone;
|
||||
while (current != null)
|
||||
{
|
||||
if (boneIndexes.TryGetValue(current, out int index))
|
||||
{
|
||||
return index;
|
||||
}
|
||||
current = current.parent;
|
||||
}
|
||||
|
||||
// 兜底到「全ての親」。
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary> Credit to pohype: https://discussions.unity.com/t/reading-meshes-at-runtime-that-are-not-enabled-for-read-write/804189/7 </summary>
|
||||
|
||||
@@ -0,0 +1,564 @@
|
||||
using LibMMD.Model;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// 将 Uma 的运行时骨架整理为 PMX 可用的标准骨架。
|
||||
/// </summary>
|
||||
internal static class PMXBoneExporter
|
||||
{
|
||||
internal sealed class Result
|
||||
{
|
||||
public Bone[] Bones { get; set; }
|
||||
public Dictionary<Transform, int> BoneIndexes { get; set; }
|
||||
}
|
||||
|
||||
private static readonly Dictionary<string, string> BoneNameMapping = new Dictionary<string, string>()
|
||||
{
|
||||
{ "Spine", "上半身" }, { "Chest", "上半身2" }, { "Neck", "首" }, { "Head", "頭" },
|
||||
{ "Shoulder_L", "左肩" }, { "Arm_L", "左腕" }, { "Elbow_L", "左ひじ" },
|
||||
{ "ArmRoll_L", "左手捩" }, { "Wrist_L", "左手首" },
|
||||
{ "Shoulder_R", "右肩" }, { "Arm_R", "右腕" }, { "Elbow_R", "右ひじ" },
|
||||
{ "ArmRoll_R", "右手捩" }, { "Wrist_R", "右手首" },
|
||||
{ "Thumb_01_L", "左親指0" }, { "Thumb_02_L", "左親指1" }, { "Thumb_03_L", "左親指2" },
|
||||
{ "Index_01_L", "左人指1" }, { "Index_02_L", "左人指2" }, { "Index_03_L", "左人指3" },
|
||||
{ "Middle_01_L", "左中指1" }, { "Middle_02_L", "左中指2" }, { "Middle_03_L", "左中指3" },
|
||||
{ "Ring_01_L", "左薬指1" }, { "Ring_02_L", "左薬指2" }, { "Ring_03_L", "左薬指3" },
|
||||
{ "Pinky_01_L", "左小指1" }, { "Pinky_02_L", "左小指2" }, { "Pinky_03_L", "左小指3" },
|
||||
{ "Thumb_01_R", "右親指0" }, { "Thumb_02_R", "右親指1" }, { "Thumb_03_R", "右親指2" },
|
||||
{ "Index_01_R", "右人指1" }, { "Index_02_R", "右人指2" }, { "Index_03_R", "右人指3" },
|
||||
{ "Middle_01_R", "右中指1" }, { "Middle_02_R", "右中指2" }, { "Middle_03_R", "右中指3" },
|
||||
{ "Ring_01_R", "右薬指1" }, { "Ring_02_R", "右薬指2" }, { "Ring_03_R", "右薬指3" },
|
||||
{ "Pinky_01_R", "右小指1" }, { "Pinky_02_R", "右小指2" }, { "Pinky_03_R", "右小指3" },
|
||||
{ "Thigh_L", "左足" }, { "Knee_L", "左ひざ" }, { "Ankle_L", "左足首" }, { "Toe_L", "左足先EX" },
|
||||
{ "Thigh_R", "右足" }, { "Knee_R", "右ひざ" }, { "Ankle_R", "右足首" }, { "Toe_R", "右足先EX" },
|
||||
{ "Eye_L", "左目" }, { "Eye_R", "右目" },
|
||||
{ "Ear_01_L", "左耳" }, { "Ear_02_L", "左耳1" }, { "Ear_03_L", "左耳2" },
|
||||
{ "Ear_01_R", "右耳" }, { "Ear_02_R", "右耳1" }, { "Ear_03_R", "右耳2" },
|
||||
{ "Mouth", "口" }, { "Jaw", "顎" }
|
||||
};
|
||||
|
||||
private static readonly string[] RequiredBoneNames =
|
||||
{
|
||||
"Hip", "Spine", "Chest", "Neck", "Head",
|
||||
"Shoulder_L", "Arm_L", "Elbow_L", "ArmRoll_L", "Wrist_L",
|
||||
"Shoulder_R", "Arm_R", "Elbow_R", "ArmRoll_R", "Wrist_R",
|
||||
"Hand_Attach_L", "Hand_Attach_R",
|
||||
"Thigh_L", "Knee_L", "Ankle_L", "Toe_L",
|
||||
"Thigh_R", "Knee_R", "Ankle_R", "Toe_R", "Eye_L", "Eye_R"
|
||||
};
|
||||
|
||||
internal static Result Build(Transform skeletonRoot, Transform coordinateRoot, IEnumerable<Renderer> renderers,
|
||||
IEnumerable<Transform> additionalBones = null)
|
||||
{
|
||||
Transform[] hierarchy = skeletonRoot.GetComponentsInChildren<Transform>(true);
|
||||
HashSet<Transform> selected = CollectReferencedBones(renderers, skeletonRoot);
|
||||
|
||||
// CySpring 的末端骨可能没有蒙皮权重,但 PMX 刚体仍需关联真实骨骼。
|
||||
if (additionalBones != null)
|
||||
{
|
||||
foreach (Transform bone in additionalBones)
|
||||
{
|
||||
if (bone != null && !IsRuntimeHelper(bone.name)) selected.Add(bone);
|
||||
}
|
||||
}
|
||||
|
||||
// 某些标准骨可能没有直接权重,但仍是动画和父链所必需的。
|
||||
foreach (string boneName in RequiredBoneNames)
|
||||
{
|
||||
Transform bone = hierarchy.FirstOrDefault(t => t.name.Equals(boneName, StringComparison.OrdinalIgnoreCase));
|
||||
if (bone != null)
|
||||
{
|
||||
selected.Add(bone);
|
||||
}
|
||||
}
|
||||
|
||||
Transform hip = Find(selected, "Hip");
|
||||
List<Bone> bones = new List<Bone>();
|
||||
Dictionary<Transform, int> indexes = new Dictionary<Transform, int>();
|
||||
Vector3 origin = coordinateRoot.InverseTransformPoint(skeletonRoot.position);
|
||||
Vector3 hipPosition = hip != null ? coordinateRoot.InverseTransformPoint(hip.position) : origin;
|
||||
|
||||
int parentOfAll = AddVirtualBone(bones, "全ての親", "ParentOfAll", origin, -1, true);
|
||||
int center = AddVirtualBone(bones, "センター", "Center", origin, parentOfAll, true);
|
||||
int groove = AddVirtualBone(bones, "グルーブ", "Groove", hipPosition, center, true);
|
||||
int waist = AddVirtualBone(bones, "腰", "Waist", hipPosition, groove, false);
|
||||
int lowerBody = AddVirtualBone(bones, "下半身", "LowerBody", hipPosition, waist, false);
|
||||
|
||||
if (skeletonRoot != null) indexes[skeletonRoot] = center;
|
||||
if (hip != null) indexes[hip] = waist;
|
||||
|
||||
foreach (Transform transform in hierarchy)
|
||||
{
|
||||
if (!selected.Contains(transform) || transform == hip || IsRuntimeHelper(transform.name))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int parentIndex = ResolveParentIndex(transform, hip, selected, indexes, waist, lowerBody);
|
||||
Bone bone = CreateTransformBone(transform, coordinateRoot, parentIndex);
|
||||
indexes[transform] = bones.Count;
|
||||
bones.Add(bone);
|
||||
}
|
||||
|
||||
int bothEyes = AddBothEyesControlBone(bones, indexes, coordinateRoot);
|
||||
ReparentTongueChain(bones, indexes);
|
||||
RebuildChildLinks(bones);
|
||||
AddFootIk(bones, indexes, coordinateRoot, parentOfAll, "L");
|
||||
AddFootIk(bones, indexes, coordinateRoot, parentOfAll, "R");
|
||||
RebuildChildLinks(bones);
|
||||
AlignElbowArmRollAndWrist(bones, indexes, coordinateRoot);
|
||||
// 必须在重建普通骨骼末端之后设置,否则挂点的显式垂直末端会被子骨关系覆盖。
|
||||
AddHandAttachmentCompatibilityBones(bones, indexes, coordinateRoot);
|
||||
SetBothEyesTailToNoseBridge(bones, bothEyes, indexes, coordinateRoot);
|
||||
Validate(bones);
|
||||
|
||||
return new Result { Bones = bones.ToArray(), BoneIndexes = indexes };
|
||||
}
|
||||
|
||||
private static int AddBothEyesControlBone(List<Bone> bones, Dictionary<Transform, int> indexes,
|
||||
Transform coordinateRoot)
|
||||
{
|
||||
Transform head = Find(indexes.Keys, "Head");
|
||||
Transform leftEye = Find(indexes.Keys, "Eye_L");
|
||||
Transform rightEye = Find(indexes.Keys, "Eye_R");
|
||||
if (head == null || (leftEye == null && rightEye == null)) return -1;
|
||||
|
||||
// Preserve the standard both-eyes control chain while reparenting both eye bones.
|
||||
int bothEyes = AddVirtualBone(
|
||||
bones,
|
||||
"\u4e21\u76ee",
|
||||
"BothEyes",
|
||||
coordinateRoot.InverseTransformPoint(head.position),
|
||||
indexes[head],
|
||||
false);
|
||||
|
||||
if (leftEye != null) bones[indexes[leftEye]].ParentIndex = bothEyes;
|
||||
if (rightEye != null) bones[indexes[rightEye]].ParentIndex = bothEyes;
|
||||
return bothEyes;
|
||||
}
|
||||
|
||||
private static void SetBothEyesTailToNoseBridge(List<Bone> bones, int bothEyes,
|
||||
Dictionary<Transform, int> indexes, Transform coordinateRoot)
|
||||
{
|
||||
if (bothEyes < 0) return;
|
||||
|
||||
Transform head = Find(indexes.Keys, "Head");
|
||||
Transform leftEye = Find(indexes.Keys, "Eye_L");
|
||||
Transform rightEye = Find(indexes.Keys, "Eye_R");
|
||||
if (head == null) return;
|
||||
|
||||
Transform nose = FindNoseBone(head);
|
||||
Vector3 noseBridgePosition;
|
||||
if (nose != null)
|
||||
{
|
||||
// Prefer a real nose bone so the endpoint follows each character face shape.
|
||||
noseBridgePosition = coordinateRoot.InverseTransformPoint(nose.position);
|
||||
}
|
||||
else if (leftEye != null && rightEye != null)
|
||||
{
|
||||
// Fall back to the eye midpoint instead of accidentally using the left eye as the endpoint.
|
||||
noseBridgePosition = coordinateRoot.InverseTransformPoint((leftEye.position + rightEye.position) * 0.5f);
|
||||
}
|
||||
else
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Bone controlBone = bones[bothEyes];
|
||||
controlBone.ChildBoneVal.ChildUseId = false;
|
||||
controlBone.ChildBoneVal.Offset = noseBridgePosition - controlBone.Position;
|
||||
}
|
||||
|
||||
private static Transform FindNoseBone(Transform head)
|
||||
{
|
||||
Transform[] descendants = head.GetComponentsInChildren<Transform>(true);
|
||||
Transform exactMatch = descendants.FirstOrDefault(t => t.name.Equals("Nose", StringComparison.OrdinalIgnoreCase));
|
||||
if (exactMatch != null) return exactMatch;
|
||||
|
||||
// Uma nose bones may include numeric suffixes; prefer the root nose bone over facial detail bones.
|
||||
return descendants.FirstOrDefault(t =>
|
||||
t.name.StartsWith("Nose_00", StringComparison.OrdinalIgnoreCase) ||
|
||||
t.name.StartsWith("Nose_01", StringComparison.OrdinalIgnoreCase) ||
|
||||
t.name.StartsWith("Nose", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
private static void AlignElbowArmRollAndWrist(List<Bone> bones,
|
||||
Dictionary<Transform, int> indexes, Transform coordinateRoot)
|
||||
{
|
||||
AlignElbowArmRollAndWrist(bones, indexes, coordinateRoot, "L");
|
||||
AlignElbowArmRollAndWrist(bones, indexes, coordinateRoot, "R");
|
||||
}
|
||||
|
||||
private static void AlignElbowArmRollAndWrist(List<Bone> bones,
|
||||
Dictionary<Transform, int> indexes, Transform coordinateRoot, string side)
|
||||
{
|
||||
Transform elbow = Find(indexes.Keys, "Elbow_" + side);
|
||||
Transform armRoll = Find(indexes.Keys, "ArmRoll_" + side);
|
||||
Transform wrist = Find(indexes.Keys, "Wrist_" + side);
|
||||
if (elbow == null || armRoll == null || wrist == null ||
|
||||
!indexes.TryGetValue(elbow, out int elbowIndex) ||
|
||||
!indexes.TryGetValue(armRoll, out int armRollIndex) ||
|
||||
!indexes.TryGetValue(wrist, out int wristIndex)) return;
|
||||
|
||||
// ArmRoll 根部是正确的腕部连接坐标:肘末端、ArmRoll 根部、手首根部必须三点重合。
|
||||
// 仅校正 PMX 输出坐标与末端指向,不改 Unity 原骨架的动画层级。
|
||||
Vector3 connectionPosition = coordinateRoot.InverseTransformPoint(armRoll.position);
|
||||
bones[armRollIndex].Position = connectionPosition;
|
||||
bones[wristIndex].Position = connectionPosition;
|
||||
bones[elbowIndex].ChildBoneVal.ChildUseId = true;
|
||||
bones[elbowIndex].ChildBoneVal.Index = wristIndex;
|
||||
}
|
||||
|
||||
private static void AddHandAttachmentCompatibilityBones(List<Bone> bones,
|
||||
Dictionary<Transform, int> indexes, Transform coordinateRoot)
|
||||
{
|
||||
AddHandAttachmentCompatibilityBone(bones, indexes, coordinateRoot, "L");
|
||||
AddHandAttachmentCompatibilityBone(bones, indexes, coordinateRoot, "R");
|
||||
}
|
||||
|
||||
private static void AddHandAttachmentCompatibilityBone(List<Bone> bones,
|
||||
Dictionary<Transform, int> indexes, Transform coordinateRoot, string side)
|
||||
{
|
||||
Transform handAttach = Find(indexes.Keys, "Hand_Attach_" + side);
|
||||
if (handAttach == null || !indexes.TryGetValue(handAttach, out int handAttachIndex)) return;
|
||||
|
||||
Vector3 attachmentPosition = coordinateRoot.InverseTransformPoint(handAttach.position);
|
||||
Vector3 tailOffset = CalculateHandAttachmentTailOffset(
|
||||
indexes.Keys, handAttach, coordinateRoot, side);
|
||||
|
||||
// 原 Hand_Attach 的位置就是掌心根部;90 度修正只作用于骨骼末端,不能移动根部。
|
||||
Bone attachmentBone = bones[handAttachIndex];
|
||||
attachmentBone.Position = attachmentPosition;
|
||||
attachmentBone.ChildBoneVal.ChildUseId = false;
|
||||
attachmentBone.ChildBoneVal.Offset = tailOffset;
|
||||
|
||||
string dummyName = side == "L" ? "ダミー.L" : "ダミー.R";
|
||||
if (bones.Any(b => b.Name.Equals(dummyName, StringComparison.OrdinalIgnoreCase))) return;
|
||||
|
||||
// 保留游戏内部 Hand_Attach,并补出外部手持场景按名称查找的兼容挂点。
|
||||
// 两骨同根、同向;父子关系仍用于继承手部运动,但不再用子骨位置定义末端。
|
||||
int dummyIndex = AddVirtualBone(
|
||||
bones,
|
||||
dummyName,
|
||||
"Dummy." + side,
|
||||
attachmentPosition,
|
||||
handAttachIndex,
|
||||
false);
|
||||
bones[dummyIndex].ChildBoneVal.ChildUseId = false;
|
||||
bones[dummyIndex].ChildBoneVal.Offset = tailOffset;
|
||||
}
|
||||
|
||||
private static Vector3 CalculateHandAttachmentTailOffset(IEnumerable<Transform> transforms,
|
||||
Transform handAttach,
|
||||
Transform coordinateRoot, string side)
|
||||
{
|
||||
Transform wrist = Find(transforms, "Wrist_" + side);
|
||||
Transform elbow = Find(transforms, "Elbow_" + side);
|
||||
if (wrist == null || elbow == null) return Vector3.up * 0.1f;
|
||||
|
||||
Transform armRoll = Find(transforms, "ArmRoll_" + side);
|
||||
// 手首导出坐标已经对齐 ArmRoll;挂点计算必须使用同一坐标源,不能继续读取旧 Wrist Transform。
|
||||
Vector3 wristPosition = coordinateRoot.InverseTransformPoint(
|
||||
armRoll != null ? armRoll.position : wrist.position);
|
||||
Vector3 elbowPosition = coordinateRoot.InverseTransformPoint(elbow.position);
|
||||
Vector3 attachmentPosition = coordinateRoot.InverseTransformPoint(handAttach.position);
|
||||
Vector3 wristToAttachment = attachmentPosition - wristPosition;
|
||||
if (wristToAttachment.sqrMagnitude < 0.000001f) return Vector3.up * 0.1f;
|
||||
|
||||
Vector3 wristBoneDirection = wristPosition - elbowPosition;
|
||||
if (wristBoneDirection.sqrMagnitude < 0.000001f) return Vector3.up * wristToAttachment.magnitude;
|
||||
|
||||
// 挂点骨以掌心为根部,末端直接垂直于手首骨(Elbow -> Wrist),而不是垂直于世界坐标。
|
||||
// 只沿模型平面旋转方向,并继续使用原 Wrist -> Hand_Attach 距离作为辅助骨长度。
|
||||
float attachmentLength = wristToAttachment.magnitude;
|
||||
Vector3 positiveCandidate =
|
||||
(Quaternion.AngleAxis(90f, Vector3.forward) * wristBoneDirection).normalized * attachmentLength;
|
||||
Vector3 negativeCandidate =
|
||||
(Quaternion.AngleAxis(-90f, Vector3.forward) * wristBoneDirection).normalized * attachmentLength;
|
||||
|
||||
string[] fingerRootNames =
|
||||
{
|
||||
"Index_01_" + side,
|
||||
"Middle_01_" + side,
|
||||
"Ring_01_" + side,
|
||||
"Pinky_01_" + side
|
||||
};
|
||||
List<Transform> fingerRoots = fingerRootNames
|
||||
.Select(name => Find(transforms, name))
|
||||
.Where(root => root != null)
|
||||
.ToList();
|
||||
if (fingerRoots.Count == 0)
|
||||
{
|
||||
// 缺少手指骨时,以原挂点相对手首的位置判断掌心侧,再选择相反方向。
|
||||
float positiveAlignment = Vector3.Dot(positiveCandidate.normalized, wristToAttachment.normalized);
|
||||
float negativeAlignment = Vector3.Dot(negativeCandidate.normalized, wristToAttachment.normalized);
|
||||
return positiveAlignment <= negativeAlignment ? positiveCandidate : negativeCandidate;
|
||||
}
|
||||
|
||||
Vector3 knuckleCenter = Vector3.zero;
|
||||
foreach (Transform fingerRoot in fingerRoots)
|
||||
{
|
||||
knuckleCenter += coordinateRoot.InverseTransformPoint(fingerRoot.position);
|
||||
}
|
||||
knuckleCenter /= fingerRoots.Count;
|
||||
|
||||
// 手调正确结果的末端背离手指,因此选择与“掌心根部 -> 四指根中心”夹角更大的候选。
|
||||
Vector3 attachmentToKnuckles = knuckleCenter - attachmentPosition;
|
||||
float positiveTowardFingers = Vector3.Dot(positiveCandidate.normalized, attachmentToKnuckles.normalized);
|
||||
float negativeTowardFingers = Vector3.Dot(negativeCandidate.normalized, attachmentToKnuckles.normalized);
|
||||
return positiveTowardFingers <= negativeTowardFingers ? positiveCandidate : negativeCandidate;
|
||||
}
|
||||
|
||||
private static HashSet<Transform> CollectReferencedBones(IEnumerable<Renderer> renderers, Transform skeletonRoot)
|
||||
{
|
||||
HashSet<Transform> weightedBones = new HashSet<Transform>();
|
||||
foreach (SkinnedMeshRenderer renderer in renderers.OfType<SkinnedMeshRenderer>())
|
||||
{
|
||||
Mesh mesh = renderer.sharedMesh;
|
||||
Transform[] rendererBones = renderer.bones;
|
||||
if (mesh == null || rendererBones == null) continue;
|
||||
|
||||
// renderer.bones 还会包含脸部占位骨;只有顶点实际使用且权重大于零时才算蒙皮引用。
|
||||
foreach (BoneWeight weight in mesh.boneWeights)
|
||||
{
|
||||
AddWeightedBone(weightedBones, rendererBones, weight.boneIndex0, weight.weight0);
|
||||
AddWeightedBone(weightedBones, rendererBones, weight.boneIndex1, weight.weight1);
|
||||
AddWeightedBone(weightedBones, rendererBones, weight.boneIndex2, weight.weight2);
|
||||
AddWeightedBone(weightedBones, rendererBones, weight.boneIndex3, weight.weight3);
|
||||
}
|
||||
}
|
||||
|
||||
HashSet<Transform> result = new HashSet<Transform>();
|
||||
foreach (Transform weightedBone in weightedBones)
|
||||
{
|
||||
// 无直接权重的 offset/连接骨仍可能是有效父链,必须补齐到骨架根节点。
|
||||
Transform current = weightedBone;
|
||||
while (current != null)
|
||||
{
|
||||
// skeletonRoot 已映射到虚拟“センター”,不能再作为普通骨重复导出。
|
||||
if (current == skeletonRoot) break;
|
||||
if (!IsRuntimeHelper(current.name)) result.Add(current);
|
||||
current = current.parent;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void AddWeightedBone(HashSet<Transform> result, Transform[] bones, int boneIndex, float weight)
|
||||
{
|
||||
const float MinimumWeight = 0.000001f;
|
||||
if (weight <= MinimumWeight || boneIndex < 0 || boneIndex >= bones.Length) return;
|
||||
|
||||
Transform bone = bones[boneIndex];
|
||||
if (bone != null && !IsRuntimeHelper(bone.name)) result.Add(bone);
|
||||
}
|
||||
|
||||
private static bool IsRuntimeHelper(string name)
|
||||
{
|
||||
return name.StartsWith("Col_", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.EndsWith("_Handle", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.EndsWith("_Pole", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.EndsWith("_Target", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.EndsWith("_Ctrl", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.IndexOf("locator", StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
}
|
||||
|
||||
private static Transform Find(IEnumerable<Transform> bones, string name)
|
||||
{
|
||||
return bones.FirstOrDefault(t => t.name.Equals(name, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
private static int ResolveParentIndex(Transform transform, Transform hip, HashSet<Transform> selected,
|
||||
Dictionary<Transform, int> indexes, int waist, int lowerBody)
|
||||
{
|
||||
Transform parent = transform.parent;
|
||||
while (parent != null && parent != hip)
|
||||
{
|
||||
if (selected.Contains(parent) && indexes.TryGetValue(parent, out int parentIndex)) return parentIndex;
|
||||
parent = parent.parent;
|
||||
}
|
||||
|
||||
if (parent == hip)
|
||||
{
|
||||
// 上半身控制链中的实际骨挂腰,其余髋部支链(腿、裙摆、尾巴)挂下半身。
|
||||
return IsUpperBodyBranch(transform, hip) ? waist : lowerBody;
|
||||
}
|
||||
return waist;
|
||||
}
|
||||
|
||||
private static bool IsUpperBodyBranch(Transform transform, Transform hip)
|
||||
{
|
||||
Transform current = transform;
|
||||
while (current != null && current != hip)
|
||||
{
|
||||
if (current.name.Equals("Spine", StringComparison.OrdinalIgnoreCase) ||
|
||||
current.name.Equals("Waist", StringComparison.OrdinalIgnoreCase) ||
|
||||
current.name.Equals("UpBody_Ctrl", StringComparison.OrdinalIgnoreCase)) return true;
|
||||
current = current.parent;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static Bone CreateTransformBone(Transform transform, Transform coordinateRoot, int parentIndex)
|
||||
{
|
||||
string mappedName;
|
||||
BoneNameMapping.TryGetValue(transform.name, out mappedName);
|
||||
return new Bone
|
||||
{
|
||||
Name = mappedName ?? transform.name,
|
||||
NameEn = transform.name,
|
||||
Position = coordinateRoot.InverseTransformPoint(transform.position),
|
||||
ParentIndex = parentIndex,
|
||||
TransformLevel = 0,
|
||||
Rotatable = true,
|
||||
Movable = false,
|
||||
Visible = true,
|
||||
Controllable = true,
|
||||
ChildBoneVal = new Bone.ChildBone { ChildUseId = false, Offset = Vector3.up * 0.1f }
|
||||
};
|
||||
}
|
||||
|
||||
private static int AddVirtualBone(List<Bone> bones, string name, string nameEn, Vector3 position, int parent, bool movable)
|
||||
{
|
||||
bones.Add(new Bone
|
||||
{
|
||||
Name = name,
|
||||
NameEn = nameEn,
|
||||
Position = position,
|
||||
ParentIndex = parent,
|
||||
TransformLevel = 0,
|
||||
Rotatable = true,
|
||||
Movable = movable,
|
||||
Visible = true,
|
||||
Controllable = true,
|
||||
ChildBoneVal = new Bone.ChildBone { ChildUseId = false, Offset = Vector3.up * 0.1f }
|
||||
});
|
||||
return bones.Count - 1;
|
||||
}
|
||||
|
||||
private static void RebuildChildLinks(List<Bone> bones)
|
||||
{
|
||||
for (int i = 0; i < bones.Count; i++)
|
||||
{
|
||||
int child = bones.FindIndex(b => b.ParentIndex == i);
|
||||
if (child >= 0)
|
||||
{
|
||||
bones[i].ChildBoneVal.ChildUseId = true;
|
||||
bones[i].ChildBoneVal.Index = child;
|
||||
}
|
||||
else
|
||||
{
|
||||
bones[i].ChildBoneVal.ChildUseId = false;
|
||||
bones[i].ChildBoneVal.Offset = Vector3.up * 0.1f;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ReparentTongueChain(List<Bone> bones, Dictionary<Transform, int> indexes)
|
||||
{
|
||||
// 保留原导出器的舌骨兼容关系,避免拆分骨架模块后出现既有功能回退。
|
||||
Transform chin = Find(indexes.Keys, "Chin") ?? indexes.Keys.FirstOrDefault(t => t.name.StartsWith("Jaw"));
|
||||
Transform tongue = Find(indexes.Keys, "Tongue");
|
||||
Transform tongueOut01 = Find(indexes.Keys, "Tongue_Out_01");
|
||||
Transform tongueOut02 = Find(indexes.Keys, "Tongue_Out_02");
|
||||
if (chin == null) return;
|
||||
|
||||
if (tongue != null)
|
||||
{
|
||||
bones[indexes[tongue]].ParentIndex = indexes[chin];
|
||||
if (tongueOut01 != null) bones[indexes[tongueOut01]].ParentIndex = indexes[tongue];
|
||||
if (tongueOut01 != null && tongueOut02 != null) bones[indexes[tongueOut02]].ParentIndex = indexes[tongueOut01];
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (Transform candidate in indexes.Keys.Where(t => t.name.StartsWith("Tongue") && !t.name.Contains("Out")))
|
||||
{
|
||||
bones[indexes[candidate]].ParentIndex = indexes[chin];
|
||||
}
|
||||
}
|
||||
|
||||
private static void AddFootIk(List<Bone> bones, Dictionary<Transform, int> indexes,
|
||||
Transform coordinateRoot, int parentOfAll, string side)
|
||||
{
|
||||
Transform thigh = Find(indexes.Keys, "Thigh_" + side);
|
||||
Transform knee = Find(indexes.Keys, "Knee_" + side);
|
||||
Transform ankle = Find(indexes.Keys, "Ankle_" + side);
|
||||
Transform toe = Find(indexes.Keys, "Toe_" + side);
|
||||
if (thigh == null || knee == null || ankle == null) return;
|
||||
|
||||
string prefix = side == "L" ? "左" : "右";
|
||||
Vector3 anklePosition = coordinateRoot.InverseTransformPoint(ankle.position);
|
||||
Vector3 ikParentPosition = new Vector3(anklePosition.x, 0, anklePosition.z);
|
||||
int ikParent = AddVirtualBone(bones, prefix + "足IK親", "FootIKParent_" + side, ikParentPosition, parentOfAll, true);
|
||||
int footIk = AddVirtualBone(bones, prefix + "足IK", "FootIK_" + side, anklePosition, ikParent, true);
|
||||
bones[footIk].HasIk = true;
|
||||
bones[footIk].TransformLevel = 1;
|
||||
bones[footIk].IkInfoVal = new Bone.IkInfo
|
||||
{
|
||||
IkTargetIndex = indexes[ankle],
|
||||
CcdIterateLimit = 40,
|
||||
CcdAngleLimit = 2.0f,
|
||||
IkLinks = new[]
|
||||
{
|
||||
// 按 PMX 文件坐标语义使用负 X 区间,限制膝盖只向预期方向弯曲。
|
||||
new Bone.IkLink { LinkIndex = indexes[knee], HasLimit = true, LoLimit = new Vector3(-Mathf.PI, 0, 0), HiLimit = new Vector3(-0.0087f, 0, 0) },
|
||||
new Bone.IkLink { LinkIndex = indexes[thigh], HasLimit = false }
|
||||
}
|
||||
};
|
||||
|
||||
if (toe == null) return;
|
||||
int toeIk = AddVirtualBone(bones, prefix + "つま先IK", "ToeIK_" + side,
|
||||
coordinateRoot.InverseTransformPoint(toe.position), footIk, true);
|
||||
bones[toeIk].HasIk = true;
|
||||
bones[toeIk].TransformLevel = 1;
|
||||
bones[toeIk].IkInfoVal = new Bone.IkInfo
|
||||
{
|
||||
IkTargetIndex = indexes[toe],
|
||||
CcdIterateLimit = 3,
|
||||
CcdAngleLimit = 1.0f,
|
||||
IkLinks = new[] { new Bone.IkLink { LinkIndex = indexes[ankle], HasLimit = false } }
|
||||
};
|
||||
}
|
||||
|
||||
private static void Validate(List<Bone> bones)
|
||||
{
|
||||
for (int i = 0; i < bones.Count; i++)
|
||||
{
|
||||
Bone bone = bones[i];
|
||||
if (bone.ParentIndex < -1 || bone.ParentIndex >= bones.Count || bone.ParentIndex == i)
|
||||
throw new InvalidOperationException("PMX 骨骼父索引无效: " + bone.Name);
|
||||
if (bone.ChildBoneVal.ChildUseId && (bone.ChildBoneVal.Index < 0 || bone.ChildBoneVal.Index >= bones.Count))
|
||||
throw new InvalidOperationException("PMX 骨骼尾端索引无效: " + bone.Name);
|
||||
if (bone.HasIk && (bone.IkInfoVal == null || bone.IkInfoVal.IkTargetIndex < 0 || bone.IkInfoVal.IkTargetIndex >= bones.Count))
|
||||
throw new InvalidOperationException("PMX IK 目标索引无效: " + bone.Name);
|
||||
if (!bone.HasIk) continue;
|
||||
|
||||
foreach (Bone.IkLink link in bone.IkInfoVal.IkLinks)
|
||||
{
|
||||
if (link.LinkIndex < 0 || link.LinkIndex >= bones.Count)
|
||||
throw new InvalidOperationException("PMX IK 链接索引无效: " + bone.Name);
|
||||
if (!link.HasLimit) continue;
|
||||
ValidateIkLimit(link.LoLimit, link.HiLimit, bone.Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void ValidateIkLimit(Vector3 lower, Vector3 upper, string boneName)
|
||||
{
|
||||
if (!IsFinite(lower) || !IsFinite(upper))
|
||||
throw new InvalidOperationException("PMX IK 角度限制包含 NaN 或 Infinity: " + boneName);
|
||||
if (lower.x > upper.x || lower.y > upper.y || lower.z > upper.z)
|
||||
throw new InvalidOperationException("PMX IK 角度限制上下限倒置: " + boneName);
|
||||
}
|
||||
|
||||
private static bool IsFinite(Vector3 value)
|
||||
{
|
||||
return !float.IsNaN(value.x) && !float.IsInfinity(value.x) &&
|
||||
!float.IsNaN(value.y) && !float.IsInfinity(value.y) &&
|
||||
!float.IsNaN(value.z) && !float.IsInfinity(value.z);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 6ef5bb0405754f1dbd085e27db72c198
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,228 @@
|
||||
using System;
|
||||
using Gallop;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// 冻结 PMX 导出瞬间的角色姿势,并在导出结束后恢复运行时状态。
|
||||
/// </summary>
|
||||
internal sealed class PMXExportStateSnapshot : IDisposable
|
||||
{
|
||||
private const float MmdAPoseArmAngle = 38.5f;
|
||||
|
||||
private readonly UmaContainerCharacter _container;
|
||||
private readonly TransformState[] _transforms;
|
||||
private readonly MorphState[] _morphs;
|
||||
private readonly BindPropertyState[] _bindProperties;
|
||||
private readonly FaceOverrideData _faceOverrideData;
|
||||
private readonly bool _bodyAnimatorEnabled;
|
||||
private readonly bool _faceAnimatorEnabled;
|
||||
private readonly bool _physicsEnabled;
|
||||
private readonly bool _eyeTrackingEnabled;
|
||||
private readonly bool _animatorControlEnabled;
|
||||
private bool _disposed;
|
||||
|
||||
private struct TransformState
|
||||
{
|
||||
internal Transform Transform;
|
||||
internal Vector3 LocalPosition;
|
||||
internal Quaternion LocalRotation;
|
||||
internal Vector3 LocalScale;
|
||||
}
|
||||
|
||||
private struct MorphState
|
||||
{
|
||||
internal FacialMorph Morph;
|
||||
internal float Weight;
|
||||
internal OverrideType OverrideType;
|
||||
internal float OverrideWeight;
|
||||
}
|
||||
|
||||
private struct BindPropertyState
|
||||
{
|
||||
internal BindProperty Property;
|
||||
internal float Value;
|
||||
}
|
||||
|
||||
internal PMXExportStateSnapshot(UmaContainerCharacter container)
|
||||
{
|
||||
_container = container ?? throw new ArgumentNullException(nameof(container));
|
||||
_bodyAnimatorEnabled = container.UmaAnimator != null && container.UmaAnimator.enabled;
|
||||
_faceAnimatorEnabled = container.UmaFaceAnimator != null && container.UmaFaceAnimator.enabled;
|
||||
_physicsEnabled = container.EnablePhysics;
|
||||
_eyeTrackingEnabled = container.EnableEyeTracking;
|
||||
_animatorControlEnabled = container.isAnimatorControl;
|
||||
_faceOverrideData = container.FaceOverrideData;
|
||||
|
||||
Transform[] transforms = container.GetComponentsInChildren<Transform>(true);
|
||||
_transforms = new TransformState[transforms.Length];
|
||||
for (int i = 0; i < transforms.Length; i++)
|
||||
{
|
||||
Transform transform = transforms[i];
|
||||
_transforms[i] = new TransformState
|
||||
{
|
||||
Transform = transform,
|
||||
LocalPosition = transform.localPosition,
|
||||
LocalRotation = transform.localRotation,
|
||||
LocalScale = transform.localScale
|
||||
};
|
||||
}
|
||||
|
||||
if (container.FaceDrivenKeyTarget != null)
|
||||
{
|
||||
var allMorphs = container.FaceDrivenKeyTarget.AllMorphs;
|
||||
_morphs = new MorphState[allMorphs.Count];
|
||||
for (int i = 0; i < allMorphs.Count; i++)
|
||||
{
|
||||
FacialMorph morph = allMorphs[i];
|
||||
_morphs[i] = new MorphState
|
||||
{
|
||||
Morph = morph,
|
||||
Weight = morph.weight,
|
||||
OverrideType = morph.OverrideType,
|
||||
OverrideWeight = morph.overrideWeight
|
||||
};
|
||||
}
|
||||
|
||||
int propertyCount = 0;
|
||||
foreach (FacialOtherMorph morph in container.FaceDrivenKeyTarget.OtherMorphs)
|
||||
{
|
||||
propertyCount += morph.BindProperties.Count;
|
||||
}
|
||||
|
||||
_bindProperties = new BindPropertyState[propertyCount];
|
||||
int propertyIndex = 0;
|
||||
foreach (FacialOtherMorph morph in container.FaceDrivenKeyTarget.OtherMorphs)
|
||||
{
|
||||
foreach (BindProperty property in morph.BindProperties)
|
||||
{
|
||||
_bindProperties[propertyIndex++] = new BindPropertyState
|
||||
{
|
||||
Property = property,
|
||||
Value = property.Value
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_morphs = new MorphState[0];
|
||||
_bindProperties = new BindPropertyState[0];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
internal void FreezeForExport()
|
||||
{
|
||||
// 冻结放在导出 try 块内,任一步骤异常时都能进入 Dispose 恢复快照。
|
||||
if (_container.UmaAnimator != null) _container.UmaAnimator.enabled = false;
|
||||
if (_container.UmaFaceAnimator != null) _container.UmaFaceAnimator.enabled = false;
|
||||
_container.isAnimatorControl = false;
|
||||
_container.EnableEyeTracking = false;
|
||||
_container.SetDynamicBoneEnable(false);
|
||||
// 迷你角色会跳过 SetDynamicBoneEnable,仍需显式关闭运行时物理。
|
||||
_container.EnablePhysics = false;
|
||||
}
|
||||
|
||||
internal void ApplyMmdReferencePose()
|
||||
{
|
||||
Transform leftArm = FindTransform("Arm_L");
|
||||
Transform rightArm = FindTransform("Arm_R");
|
||||
if (_container.InitBoneTransform == null || leftArm == null || rightArm == null)
|
||||
{
|
||||
throw new InvalidOperationException("无法生成 MMD A-pose:角色缺少初始骨骼数据或左右上臂骨骼。");
|
||||
}
|
||||
|
||||
// 先回到角色初始化姿势,再按历史 VMD 导出基准将双臂各下压 38.5 度。
|
||||
_container.ResetBodyPose();
|
||||
_container.UpBodyReset();
|
||||
leftArm.Rotate(0f, 0f, -MmdAPoseArmAngle, Space.Self);
|
||||
rightArm.Rotate(0f, 0f, MmdAPoseArmAngle, Space.Self);
|
||||
}
|
||||
|
||||
private Transform FindTransform(string name)
|
||||
{
|
||||
for (int i = 0; i < _transforms.Length; i++)
|
||||
{
|
||||
Transform transform = _transforms[i].Transform;
|
||||
if (transform != null && transform.name.Equals(name, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return transform;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
|
||||
try
|
||||
{
|
||||
RestoreFacialState();
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
RestoreTransforms();
|
||||
}
|
||||
finally
|
||||
{
|
||||
RestoreRuntimeComponents();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void RestoreTransforms()
|
||||
{
|
||||
// 面部形态恢复会重新计算局部变换,随后用快照精确恢复完整层级。
|
||||
for (int i = 0; i < _transforms.Length; i++)
|
||||
{
|
||||
TransformState state = _transforms[i];
|
||||
if (state.Transform == null) continue;
|
||||
state.Transform.localPosition = state.LocalPosition;
|
||||
state.Transform.localRotation = state.LocalRotation;
|
||||
state.Transform.localScale = state.LocalScale;
|
||||
}
|
||||
}
|
||||
|
||||
private void RestoreRuntimeComponents()
|
||||
{
|
||||
_container.isAnimatorControl = _animatorControlEnabled;
|
||||
_container.EnableEyeTracking = _eyeTrackingEnabled;
|
||||
_container.SetDynamicBoneEnable(_physicsEnabled);
|
||||
// 与冻结路径对称,确保迷你角色也恢复原始物理标记。
|
||||
_container.EnablePhysics = _physicsEnabled;
|
||||
if (_container.UmaFaceAnimator != null) _container.UmaFaceAnimator.enabled = _faceAnimatorEnabled;
|
||||
if (_container.UmaAnimator != null) _container.UmaAnimator.enabled = _bodyAnimatorEnabled;
|
||||
}
|
||||
|
||||
private void RestoreFacialState()
|
||||
{
|
||||
_container.FaceOverrideData = _faceOverrideData;
|
||||
for (int i = 0; i < _morphs.Length; i++)
|
||||
{
|
||||
MorphState state = _morphs[i];
|
||||
state.Morph.weight = state.Weight;
|
||||
state.Morph.OverrideType = state.OverrideType;
|
||||
state.Morph.overrideWeight = state.OverrideWeight;
|
||||
}
|
||||
for (int i = 0; i < _bindProperties.Length; i++)
|
||||
{
|
||||
BindPropertyState state = _bindProperties[i];
|
||||
state.Property.Value = state.Value;
|
||||
}
|
||||
|
||||
// 恢复材质、显隐和泪光等非 Transform 表情副作用。
|
||||
_container.FaceDrivenKeyTarget?.ChangeMorph();
|
||||
|
||||
// ChangeMorph 可能重算覆盖字段,数据层仍应保持导出前的原值。
|
||||
for (int i = 0; i < _morphs.Length; i++)
|
||||
{
|
||||
MorphState state = _morphs[i];
|
||||
state.Morph.OverrideType = state.OverrideType;
|
||||
state.Morph.overrideWeight = state.OverrideWeight;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 3f9b6710a2b24afebed437093b88c5a1
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,724 @@
|
||||
using Gallop;
|
||||
using LibMMD.Model;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// 将 CySpring 头发、耳朵、尾巴等物理骨骼链转换为 PMX 2.0 原生刚体与 Joint。
|
||||
/// 严格基于骨骼局部坐标空间计算刚体姿态,消除全局增量误差与自旋偏差。
|
||||
/// </summary>
|
||||
internal static class PMXPhysicsExporter
|
||||
{
|
||||
// 碰撞组定义:使用独立组并关闭组内碰撞,避免受 Joint 约束的相邻刚体互相挤压
|
||||
internal const int DynamicCollisionGroup = 3;
|
||||
internal const int TailBodyCollisionGroup = 2;
|
||||
internal const int SkirtCollisionGroup = 4;
|
||||
internal const int SkirtLegCollisionGroup = 5;
|
||||
|
||||
internal const float DefaultRadius = 0.018f;
|
||||
internal const float MinimumRadius = 0.006f;
|
||||
internal const float MaximumRadius = 0.045f;
|
||||
internal const float MinimumSegmentLength = 0.004f;
|
||||
|
||||
// 尾巴摆幅与弹簧参数
|
||||
private const float TailFreeBendDegrees = 75f;
|
||||
private const float TailFreeTwistDegrees = 30f;
|
||||
private const float TailRootBendSpring = 12f;
|
||||
private const float TailTipBendSpring = 4f;
|
||||
private const float TailRootTwistSpring = 4f;
|
||||
private const float TailTipTwistSpring = 1.5f;
|
||||
private const float TailColliderClearanceMultiplier = 1.5f;
|
||||
private const float TailColliderMinimumRadiusMultiplier = 1.25f;
|
||||
private const float TailColliderMaximumRadius = 0.12f;
|
||||
|
||||
// 普通发束物理预设
|
||||
internal static readonly PhysicsPreset DefaultPreset = new PhysicsPreset
|
||||
{
|
||||
RootMass = 0.8f,
|
||||
TipMass = 0.25f,
|
||||
RootTranslateDamp = 0.68f,
|
||||
TipTranslateDamp = 0.88f,
|
||||
RootRotateDamp = 0.76f,
|
||||
TipRotateDamp = 0.92f,
|
||||
BendLimitDegrees = 18f,
|
||||
TwistLimitDegrees = 8f,
|
||||
BendSpring = 12f,
|
||||
TwistSpring = 5f
|
||||
};
|
||||
|
||||
// 耳朵物理预设:硬附属骨,限制小角度快速回正
|
||||
internal static readonly PhysicsPreset EarPreset = new PhysicsPreset
|
||||
{
|
||||
RootMass = 0.65f,
|
||||
TipMass = 0.3f,
|
||||
RootTranslateDamp = 0.82f,
|
||||
TipTranslateDamp = 0.94f,
|
||||
RootRotateDamp = 0.88f,
|
||||
TipRotateDamp = 0.96f,
|
||||
BendLimitDegrees = 9f,
|
||||
TwistLimitDegrees = 4.5f,
|
||||
BendSpring = 20f,
|
||||
TwistSpring = 9f
|
||||
};
|
||||
|
||||
// 尾巴物理预设
|
||||
internal static readonly PhysicsPreset TailPreset = new PhysicsPreset
|
||||
{
|
||||
RootMass = 0.9f,
|
||||
TipMass = 0.28f,
|
||||
RootTranslateDamp = 0.72f,
|
||||
TipTranslateDamp = 0.86f,
|
||||
RootRotateDamp = 0.72f,
|
||||
TipRotateDamp = 0.88f,
|
||||
BendLimitDegrees = TailFreeBendDegrees,
|
||||
TwistLimitDegrees = TailFreeTwistDegrees,
|
||||
BendSpring = TailRootBendSpring,
|
||||
TwistSpring = TailRootTwistSpring
|
||||
};
|
||||
|
||||
// 裙摆物理预设
|
||||
internal static readonly PhysicsPreset SkirtPreset = new PhysicsPreset
|
||||
{
|
||||
RootMass = 0.7f,
|
||||
TipMass = 0.3f,
|
||||
RootTranslateDamp = 0.82f,
|
||||
TipTranslateDamp = 0.92f,
|
||||
RootRotateDamp = 0.86f,
|
||||
TipRotateDamp = 0.95f,
|
||||
BendLimitDegrees = 16f,
|
||||
TwistLimitDegrees = 6f,
|
||||
BendSpring = 22f,
|
||||
TwistSpring = 9f
|
||||
};
|
||||
|
||||
internal sealed class PhysicsPreset
|
||||
{
|
||||
internal float RootMass;
|
||||
internal float TipMass;
|
||||
internal float RootTranslateDamp;
|
||||
internal float TipTranslateDamp;
|
||||
internal float RootRotateDamp;
|
||||
internal float TipRotateDamp;
|
||||
internal float BendLimitDegrees;
|
||||
internal float TwistLimitDegrees;
|
||||
internal float BendSpring;
|
||||
internal float TwistSpring;
|
||||
}
|
||||
|
||||
internal sealed class Context
|
||||
{
|
||||
internal readonly List<Chain> Chains = new List<Chain>();
|
||||
internal readonly List<SkirtColumn> SkirtColumns = new List<SkirtColumn>();
|
||||
internal readonly HashSet<Transform> DynamicBones = new HashSet<Transform>();
|
||||
internal SkirtController SkirtController;
|
||||
}
|
||||
|
||||
internal sealed class Chain
|
||||
{
|
||||
internal Transform Root;
|
||||
internal bool IsEar;
|
||||
internal bool IsTail;
|
||||
internal readonly HashSet<Transform> Bones = new HashSet<Transform>();
|
||||
internal readonly Dictionary<Transform, float> Radii = new Dictionary<Transform, float>();
|
||||
}
|
||||
|
||||
internal sealed class SkirtColumn
|
||||
{
|
||||
internal Chain Chain;
|
||||
internal bool IsCheckRightLeg;
|
||||
internal bool IsCheckLeftLeg;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解析角色中的物理链与裙摆数据。
|
||||
/// </summary>
|
||||
internal static Context Prepare(UmaContainerCharacter character, Transform skeletonRoot)
|
||||
{
|
||||
Context context = new Context();
|
||||
if (character == null || skeletonRoot == null || character.cySpringDataContainers == null)
|
||||
return context;
|
||||
|
||||
Transform[] hierarchy = skeletonRoot.GetComponentsInChildren<Transform>(true);
|
||||
HashSet<Transform> claimedBones = new HashSet<Transform>();
|
||||
context.SkirtController = character.GetComponent<SkirtController>() ??
|
||||
character.GetComponentInChildren<SkirtController>(true);
|
||||
|
||||
// 优先收集裙摆网格列
|
||||
PMXSkirtPhysicsExporter.CollectSkirtColumns(character, skeletonRoot, context, claimedBones);
|
||||
|
||||
// 遍历 CySpring 容器收集头发、耳朵、尾巴链
|
||||
foreach (CySpringDataContainer container in character.cySpringDataContainers)
|
||||
{
|
||||
if (container == null || container.springParam == null) continue;
|
||||
|
||||
foreach (CySpringParamDataElement element in container.springParam)
|
||||
{
|
||||
if (!IsLinearPhysicsElement(container, element)) continue;
|
||||
|
||||
// 若该骨骼已被上游链或裙摆占用,跳过以避免生成重复重叠子链
|
||||
Transform root = FindRootTransform(element._boneName, hierarchy);
|
||||
if (root == null || claimedBones.Contains(root)) continue;
|
||||
|
||||
Chain chain = BuildChain(element, root, claimedBones);
|
||||
if (chain == null || chain.Bones.Count == 0) continue;
|
||||
|
||||
claimedBones.UnionWith(chain.Bones);
|
||||
context.Chains.Add(chain);
|
||||
context.DynamicBones.UnionWith(chain.Bones);
|
||||
}
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 构建所有 PMX 刚体与 Joint。
|
||||
/// </summary>
|
||||
internal static void Build(Context context, Transform coordinateRoot, PMXBoneExporter.Result boneResult,
|
||||
RawMMDModel model)
|
||||
{
|
||||
List<MMDRigidBody> rigidBodies = new List<MMDRigidBody>();
|
||||
List<MMDJoint> joints = new List<MMDJoint>();
|
||||
Dictionary<Transform, int> dynamicRigidIndexes = new Dictionary<Transform, int>();
|
||||
|
||||
foreach (Chain chain in context.Chains)
|
||||
{
|
||||
BuildChainPhysics(chain, coordinateRoot, boneResult, rigidBodies, joints, dynamicRigidIndexes);
|
||||
}
|
||||
|
||||
PMXSkirtPhysicsExporter.BuildSkirtPhysics(
|
||||
context, coordinateRoot, boneResult, rigidBodies, joints, dynamicRigidIndexes);
|
||||
|
||||
Validate(rigidBodies, joints, boneResult.Bones.Length);
|
||||
model.Rigidbodies = rigidBodies.ToArray();
|
||||
model.Joints = joints.ToArray();
|
||||
}
|
||||
|
||||
private static Transform FindRootTransform(string boneName, Transform[] hierarchy)
|
||||
{
|
||||
if (string.IsNullOrEmpty(boneName)) return null;
|
||||
return hierarchy.FirstOrDefault(t => string.Equals(t.name, boneName, StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
private static Chain BuildChain(CySpringParamDataElement element, Transform root, HashSet<Transform> claimedBones)
|
||||
{
|
||||
if (element == null || root == null) return null;
|
||||
|
||||
Dictionary<string, float> configuredBones = new Dictionary<string, float>(StringComparer.Ordinal);
|
||||
configuredBones[element._boneName] = SanitizeRadius(element._collisionRadius);
|
||||
if (element._childElements != null)
|
||||
{
|
||||
foreach (CySpringParamDataChildElement child in element._childElements)
|
||||
{
|
||||
if (child != null && !string.IsNullOrEmpty(child._boneName))
|
||||
configuredBones[child._boneName] = SanitizeRadius(child._collisionRadius);
|
||||
}
|
||||
}
|
||||
|
||||
Chain chain = new Chain
|
||||
{
|
||||
Root = root,
|
||||
IsEar = configuredBones.Keys.Any(IsEarBoneName),
|
||||
IsTail = configuredBones.Keys.Any(IsTailBoneName)
|
||||
};
|
||||
|
||||
CollectContinuousBones(root, configuredBones, chain, claimedBones);
|
||||
return chain.Bones.Count > 0 ? chain : null;
|
||||
}
|
||||
|
||||
internal static void CollectContinuousBones(Transform bone, Dictionary<string, float> configuredBones,
|
||||
Chain chain, HashSet<Transform> claimedBones = null)
|
||||
{
|
||||
if (!configuredBones.TryGetValue(bone.name, out float radius)) return;
|
||||
if (claimedBones != null && claimedBones.Contains(bone)) return;
|
||||
|
||||
chain.Bones.Add(bone);
|
||||
chain.Radii[bone] = radius;
|
||||
for (int i = 0; i < bone.childCount; i++)
|
||||
{
|
||||
Transform child = bone.GetChild(i);
|
||||
if (configuredBones.ContainsKey(child.name))
|
||||
CollectContinuousBones(child, configuredBones, chain, claimedBones);
|
||||
}
|
||||
}
|
||||
|
||||
private static void BuildChainPhysics(Chain chain, Transform coordinateRoot, PMXBoneExporter.Result boneResult,
|
||||
List<MMDRigidBody> rigidBodies, List<MMDJoint> joints,
|
||||
Dictionary<Transform, int> dynamicRigidIndexes)
|
||||
{
|
||||
if (!boneResult.BoneIndexes.ContainsKey(chain.Root)) return;
|
||||
|
||||
PhysicsPreset preset = chain.IsEar ? EarPreset : chain.IsTail ? TailPreset : DefaultPreset;
|
||||
Transform anchorBone = FindNearestExportedParentTransform(chain.Root.parent, boneResult.BoneIndexes);
|
||||
int anchorBoneIndex = anchorBone != null ? boneResult.BoneIndexes[anchorBone] : 0;
|
||||
int anchorIndex = rigidBodies.Count;
|
||||
|
||||
// 提取发根相对于模型基准坐标系的旋转
|
||||
Quaternion rootBoneWorldRot = Quaternion.Inverse(coordinateRoot.rotation) * chain.Root.rotation;
|
||||
Transform firstChild = GetChainChildren(chain.Root, chain.Bones).FirstOrDefault();
|
||||
Vector3 localDirToChild = firstChild != null
|
||||
? chain.Root.InverseTransformPoint(firstChild.position)
|
||||
: Vector3.down;
|
||||
if (localDirToChild.sqrMagnitude < 0.000001f) localDirToChild = Vector3.down;
|
||||
|
||||
Quaternion anchorRotation = rootBoneWorldRot * Quaternion.FromToRotation(Vector3.up, localDirToChild.normalized);
|
||||
rigidBodies.Add(CreateAnchorBody(chain, coordinateRoot, anchorBoneIndex, ConvertUnityRotationToWriterEuler(anchorRotation)));
|
||||
|
||||
if (chain.IsTail)
|
||||
{
|
||||
MMDRigidBody bodyCollider = CreateTailBodyCollider(chain, coordinateRoot, anchorBone, anchorBoneIndex);
|
||||
if (bodyCollider != null) rigidBodies.Add(bodyCollider);
|
||||
}
|
||||
|
||||
List<Transform> orderedBones = chain.Bones.OrderBy(GetDepth).ToList();
|
||||
int maximumDepth = orderedBones.Count > 0 ? orderedBones.Max(GetDepth) - GetDepth(chain.Root) : 0;
|
||||
float jointBendLimit = preset.BendLimitDegrees;
|
||||
float jointTwistLimit = preset.TwistLimitDegrees;
|
||||
|
||||
foreach (Transform bone in orderedBones)
|
||||
{
|
||||
if (!boneResult.BoneIndexes.TryGetValue(bone, out int boneIndex) || dynamicRigidIndexes.ContainsKey(bone))
|
||||
continue;
|
||||
|
||||
List<Transform> children = GetChainChildren(bone, chain.Bones);
|
||||
Transform singleChild = children.Count > 0 ? children[0] : null;
|
||||
|
||||
float depthRatio = maximumDepth > 0
|
||||
? Mathf.Clamp01((GetDepth(bone) - GetDepth(chain.Root)) / (float)maximumDepth)
|
||||
: 1f;
|
||||
int rigidIndex = rigidBodies.Count;
|
||||
|
||||
// 严格基于骨骼自身局部空间计算胶囊体刚体朝向与中心
|
||||
MMDRigidBody dynamicBody = CreateDynamicBodyLocalSpace(
|
||||
bone, singleChild, chain.Radii[bone], depthRatio, coordinateRoot, boneIndex, preset, chain.Bones);
|
||||
rigidBodies.Add(dynamicBody);
|
||||
dynamicRigidIndexes[bone] = rigidIndex;
|
||||
|
||||
int parentRigidIndex = (bone == chain.Root)
|
||||
? anchorIndex
|
||||
: FindParentRigidIndex(bone.parent, chain.Bones, dynamicRigidIndexes, anchorIndex);
|
||||
|
||||
float bendSpring = chain.IsTail
|
||||
? Mathf.Lerp(TailRootBendSpring, TailTipBendSpring, depthRatio)
|
||||
: preset.BendSpring;
|
||||
float twistSpring = chain.IsTail
|
||||
? Mathf.Lerp(TailRootTwistSpring, TailTipTwistSpring, depthRatio)
|
||||
: preset.TwistSpring;
|
||||
|
||||
// Joint 锚点严格对齐骨骼节点位置,旋转与刚体局部空间物理姿态精确同步
|
||||
joints.Add(CreateJoint(
|
||||
bone, coordinateRoot, parentRigidIndex, rigidIndex,
|
||||
dynamicBody.Rotation, jointBendLimit, jointTwistLimit, bendSpring, twistSpring));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 严格基于骨骼本地坐标系构建刚体,消除跨骨段增量误差,并支持末端叶骨切线平滑延伸。
|
||||
/// </summary>
|
||||
private static MMDRigidBody CreateDynamicBodyLocalSpace(Transform bone, Transform child, float configuredRadius,
|
||||
float depthRatio, Transform coordinateRoot, int boneIndex, PhysicsPreset preset, HashSet<Transform> chainBones)
|
||||
{
|
||||
Vector3 start = coordinateRoot.InverseTransformPoint(bone.position);
|
||||
Quaternion boneRotInCoord = Quaternion.Inverse(coordinateRoot.rotation) * bone.rotation;
|
||||
|
||||
if (child != null)
|
||||
{
|
||||
// 有子骨段:在骨骼局部空间求出指向子骨的局部方向
|
||||
Vector3 localChildPos = bone.InverseTransformPoint(child.position);
|
||||
float length = localChildPos.magnitude;
|
||||
Vector3 localDir = length > 0.000001f ? localChildPos / length : Vector3.down;
|
||||
|
||||
Quaternion localAlign = Quaternion.FromToRotation(Vector3.up, localDir);
|
||||
Quaternion capsuleRot = boneRotInCoord * localAlign;
|
||||
|
||||
Vector3 position = coordinateRoot.InverseTransformPoint(bone.TransformPoint(localChildPos * 0.5f));
|
||||
float radius = Mathf.Clamp(configuredRadius, MinimumRadius, MaximumRadius);
|
||||
if (length > MinimumSegmentLength)
|
||||
radius = Mathf.Min(radius, Mathf.Max(MinimumRadius, length * 0.28f));
|
||||
|
||||
float cylinderLength = GetCapsuleCylinderLength(length, radius);
|
||||
Vector3 rotationEuler = ConvertUnityRotationToWriterEuler(capsuleRot);
|
||||
|
||||
return CreateCapsuleBody(bone.name, boneIndex, radius, cylinderLength, position, rotationEuler, depthRatio, preset);
|
||||
}
|
||||
|
||||
// 末端叶骨(无子骨):沿父骨到当前骨的局部切线方向延伸包裹发梢
|
||||
if (bone.parent != null && chainBones.Contains(bone.parent))
|
||||
{
|
||||
Transform parentBone = bone.parent;
|
||||
Vector3 worldDirFromParent = bone.position - parentBone.position;
|
||||
float parentDist = worldDirFromParent.magnitude;
|
||||
|
||||
Vector3 localDir = bone.InverseTransformDirection(worldDirFromParent);
|
||||
if (localDir.sqrMagnitude < 0.000001f) localDir = Vector3.down;
|
||||
else localDir.Normalize();
|
||||
|
||||
Quaternion localAlign = Quaternion.FromToRotation(Vector3.up, localDir);
|
||||
Quaternion capsuleRot = boneRotInCoord * localAlign;
|
||||
|
||||
float length = Mathf.Clamp(parentDist * 0.6f, MinimumSegmentLength, MaximumRadius * 2.5f);
|
||||
float radius = Mathf.Clamp(configuredRadius, MinimumRadius, MaximumRadius);
|
||||
radius = Mathf.Min(radius, Mathf.Max(MinimumRadius, length * 0.32f));
|
||||
|
||||
Vector3 centerWorld = bone.position + (worldDirFromParent.normalized * (length * 0.5f));
|
||||
Vector3 position = coordinateRoot.InverseTransformPoint(centerWorld);
|
||||
float cylinderLength = GetCapsuleCylinderLength(length, radius);
|
||||
Vector3 rotationEuler = ConvertUnityRotationToWriterEuler(capsuleRot);
|
||||
|
||||
return CreateCapsuleBody(bone.name, boneIndex, radius, cylinderLength, position, rotationEuler, depthRatio, preset);
|
||||
}
|
||||
|
||||
// 单节点孤立骨骼:使用球体刚体
|
||||
float sphereRadius = Mathf.Clamp(configuredRadius, MinimumRadius, MaximumRadius);
|
||||
Vector3 sphereRotation = ConvertUnityRotationToWriterEuler(boneRotInCoord);
|
||||
return new MMDRigidBody
|
||||
{
|
||||
Name = bone.name + "_physics",
|
||||
NameEn = bone.name + "_physics",
|
||||
AssociatedBoneIndex = boneIndex,
|
||||
CollisionGroup = DynamicCollisionGroup,
|
||||
CollisionMask = CreateCollisionMaskExcludingGroups(
|
||||
DynamicCollisionGroup, SkirtCollisionGroup, SkirtLegCollisionGroup),
|
||||
Shape = MMDRigidBody.RigidBodyShape.RigidShapeSphere,
|
||||
Dimemsions = new Vector3(sphereRadius, 0, 0),
|
||||
Position = start,
|
||||
Rotation = sphereRotation,
|
||||
Mass = Mathf.Lerp(preset.RootMass, preset.TipMass, depthRatio),
|
||||
TranslateDamp = Mathf.Lerp(preset.RootTranslateDamp, preset.TipTranslateDamp, depthRatio),
|
||||
RotateDamp = Mathf.Lerp(preset.RootRotateDamp, preset.TipRotateDamp, depthRatio),
|
||||
Restitution = 0,
|
||||
Friction = 0,
|
||||
Type = MMDRigidBody.RigidBodyType.RigidTypePhysics
|
||||
};
|
||||
}
|
||||
|
||||
private static MMDRigidBody CreateCapsuleBody(string boneName, int boneIndex, float radius,
|
||||
float cylinderLength, Vector3 position, Vector3 rotationEuler, float depthRatio, PhysicsPreset preset)
|
||||
{
|
||||
return new MMDRigidBody
|
||||
{
|
||||
Name = boneName + "_physics",
|
||||
NameEn = boneName + "_physics",
|
||||
AssociatedBoneIndex = boneIndex,
|
||||
CollisionGroup = DynamicCollisionGroup,
|
||||
CollisionMask = CreateCollisionMaskExcludingGroups(
|
||||
DynamicCollisionGroup, SkirtCollisionGroup, SkirtLegCollisionGroup),
|
||||
Shape = MMDRigidBody.RigidBodyShape.RigidShapeCapsule,
|
||||
Dimemsions = new Vector3(radius, cylinderLength, 0),
|
||||
Position = position,
|
||||
Rotation = rotationEuler,
|
||||
Mass = Mathf.Lerp(preset.RootMass, preset.TipMass, depthRatio),
|
||||
TranslateDamp = Mathf.Lerp(preset.RootTranslateDamp, preset.TipTranslateDamp, depthRatio),
|
||||
RotateDamp = Mathf.Lerp(preset.RootRotateDamp, preset.TipRotateDamp, depthRatio),
|
||||
Restitution = 0,
|
||||
Friction = 0,
|
||||
Type = MMDRigidBody.RigidBodyType.RigidTypePhysics
|
||||
};
|
||||
}
|
||||
|
||||
private static MMDRigidBody CreateAnchorBody(Chain chain, Transform coordinateRoot, int boneIndex, Vector3 rotation)
|
||||
{
|
||||
float radius = Mathf.Max(MinimumRadius, chain.Radii[chain.Root] * 0.75f);
|
||||
return new MMDRigidBody
|
||||
{
|
||||
Name = chain.Root.name + "_anchor",
|
||||
NameEn = chain.Root.name + "_anchor",
|
||||
AssociatedBoneIndex = boneIndex,
|
||||
CollisionGroup = DynamicCollisionGroup,
|
||||
CollisionMask = CreateCollisionMaskExcludingGroups(
|
||||
DynamicCollisionGroup, SkirtCollisionGroup, SkirtLegCollisionGroup),
|
||||
Shape = MMDRigidBody.RigidBodyShape.RigidShapeSphere,
|
||||
Dimemsions = new Vector3(radius, 0, 0),
|
||||
Position = coordinateRoot.InverseTransformPoint(chain.Root.position),
|
||||
Rotation = rotation,
|
||||
Mass = 0,
|
||||
TranslateDamp = 1,
|
||||
RotateDamp = 1,
|
||||
Restitution = 0,
|
||||
Friction = 0,
|
||||
Type = MMDRigidBody.RigidBodyType.RigidTypeKinematic
|
||||
};
|
||||
}
|
||||
|
||||
private static MMDRigidBody CreateTailBodyCollider(Chain chain, Transform coordinateRoot,
|
||||
Transform anchorBone, int anchorBoneIndex)
|
||||
{
|
||||
if (anchorBone == null) return null;
|
||||
|
||||
Vector3 rootPosition = coordinateRoot.InverseTransformPoint(chain.Root.position);
|
||||
Vector3 anchorPosition = coordinateRoot.InverseTransformPoint(anchorBone.position);
|
||||
float rootDistance = Vector3.Distance(rootPosition, anchorPosition);
|
||||
float tailRadius = chain.Radii[chain.Root];
|
||||
if (rootDistance <= MinimumSegmentLength) return null;
|
||||
|
||||
float radius = Mathf.Clamp(
|
||||
rootDistance - tailRadius * TailColliderClearanceMultiplier,
|
||||
tailRadius * TailColliderMinimumRadiusMultiplier,
|
||||
TailColliderMaximumRadius);
|
||||
|
||||
return new MMDRigidBody
|
||||
{
|
||||
Name = chain.Root.name + "_body_blocker",
|
||||
NameEn = chain.Root.name + "_body_blocker",
|
||||
AssociatedBoneIndex = anchorBoneIndex,
|
||||
CollisionGroup = TailBodyCollisionGroup,
|
||||
CollisionMask = CreateCollisionMaskExcludingGroups(
|
||||
TailBodyCollisionGroup, SkirtCollisionGroup, SkirtLegCollisionGroup),
|
||||
Shape = MMDRigidBody.RigidBodyShape.RigidShapeSphere,
|
||||
Dimemsions = new Vector3(radius, 0, 0),
|
||||
Position = anchorPosition,
|
||||
Rotation = Vector3.zero,
|
||||
Mass = 0,
|
||||
TranslateDamp = 1,
|
||||
RotateDamp = 1,
|
||||
Restitution = 0,
|
||||
Friction = 0.5f,
|
||||
Type = MMDRigidBody.RigidBodyType.RigidTypeKinematic
|
||||
};
|
||||
}
|
||||
|
||||
private static MMDJoint CreateJoint(Transform bone, Transform coordinateRoot,
|
||||
int parentRigidIndex, int rigidIndex, Vector3 jointRotation, float bendLimitDegrees,
|
||||
float twistLimitDegrees, float bendSpring, float twistSpring)
|
||||
{
|
||||
float bend = bendLimitDegrees * Mathf.Deg2Rad;
|
||||
float twist = twistLimitDegrees * Mathf.Deg2Rad;
|
||||
Vector3 rotationLowLimit = new Vector3(-bend, -twist, -bend);
|
||||
Vector3 rotationHiLimit = new Vector3(bend, twist, bend);
|
||||
|
||||
return new MMDJoint
|
||||
{
|
||||
Name = bone.name + "_joint",
|
||||
NameEn = bone.name + "_joint",
|
||||
AssociatedRigidBodyIndex = new[] { parentRigidIndex, rigidIndex },
|
||||
Position = coordinateRoot.InverseTransformPoint(bone.position),
|
||||
Rotation = jointRotation,
|
||||
PositionLowLimit = Vector3.zero,
|
||||
PositionHiLimit = Vector3.zero,
|
||||
RotationLowLimit = rotationLowLimit,
|
||||
RotationHiLimit = rotationHiLimit,
|
||||
SpringTranslate = Vector3.zero,
|
||||
SpringRotate = new Vector3(bendSpring, twistSpring, bendSpring)
|
||||
};
|
||||
}
|
||||
|
||||
internal static float GetCapsuleCylinderLength(float endpointDistance, float radius)
|
||||
{
|
||||
return Mathf.Max(MinimumSegmentLength, endpointDistance - radius * 2f);
|
||||
}
|
||||
|
||||
internal static ushort CreateCollisionMaskExcludingGroups(params int[] groups)
|
||||
{
|
||||
ushort mask = 0;
|
||||
foreach (int group in groups) mask |= (ushort)(1 << group);
|
||||
return mask;
|
||||
}
|
||||
|
||||
private static bool IsEarBoneName(string boneName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(boneName)) return false;
|
||||
string name = boneName.ToLowerInvariant();
|
||||
return name.Contains("ear") || name.Contains("mimi") || name.Contains("耳");
|
||||
}
|
||||
|
||||
private static bool IsTailBoneName(string boneName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(boneName)) return false;
|
||||
string name = boneName.ToLowerInvariant();
|
||||
return name.Contains("tail") || name.Contains("shippo") || name.Contains("尻尾") || name.Contains("尾");
|
||||
}
|
||||
|
||||
internal static Vector3 ConvertUnityRotationToWriterEuler(Quaternion unityRotation)
|
||||
{
|
||||
// 坐标基 S=diag(-1, 1, -1),完整旋转按 R_pmx=S*R_unity*S^-1 转换
|
||||
Quaternion pmxRotation = new Quaternion(
|
||||
-unityRotation.x, unityRotation.y, -unityRotation.z, unityRotation.w);
|
||||
Vector3 pmxEuler = ExtractPmxEulerDegrees(pmxRotation);
|
||||
|
||||
// Writer 落盘时执行 (x,y,z)->(-x,y,-z),此处返回内存坐标约定
|
||||
return new Vector3(
|
||||
NormalizeDegrees(-pmxEuler.x),
|
||||
NormalizeDegrees(pmxEuler.y),
|
||||
NormalizeDegrees(-pmxEuler.z));
|
||||
}
|
||||
|
||||
private static Vector3 ExtractPmxEulerDegrees(Quaternion rotation)
|
||||
{
|
||||
Matrix4x4 matrix = Matrix4x4.Rotate(rotation);
|
||||
// PMX 与 mmd_tools 使用 YXZ 欧拉旋转顺序(R = Ry * Rx * Rz)
|
||||
float x = Mathf.Asin(Mathf.Clamp(-matrix.m12, -1f, 1f));
|
||||
float cosX = Mathf.Cos(x);
|
||||
float y;
|
||||
float z;
|
||||
|
||||
if (Mathf.Abs(cosX) > 0.00001f)
|
||||
{
|
||||
y = Mathf.Atan2(matrix.m02, matrix.m22);
|
||||
z = Mathf.Atan2(matrix.m10, matrix.m11);
|
||||
}
|
||||
else
|
||||
{
|
||||
y = Mathf.Atan2(matrix.m01, matrix.m00);
|
||||
z = 0f;
|
||||
}
|
||||
|
||||
return new Vector3(x, y, z) * Mathf.Rad2Deg;
|
||||
}
|
||||
|
||||
private static float NormalizeDegrees(float value)
|
||||
{
|
||||
return value > 180f ? value - 360f : value;
|
||||
}
|
||||
|
||||
internal static List<Transform> GetChainChildren(Transform bone, HashSet<Transform> chainBones)
|
||||
{
|
||||
List<Transform> result = new List<Transform>();
|
||||
for (int i = 0; i < bone.childCount; i++)
|
||||
{
|
||||
Transform child = bone.GetChild(i);
|
||||
if (chainBones.Contains(child)) result.Add(child);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static Transform GetSingleChainChild(Transform bone, HashSet<Transform> chainBones)
|
||||
{
|
||||
Transform result = null;
|
||||
for (int i = 0; i < bone.childCount; i++)
|
||||
{
|
||||
Transform child = bone.GetChild(i);
|
||||
if (!chainBones.Contains(child)) continue;
|
||||
if (result != null) return null;
|
||||
result = child;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static int FindParentRigidIndex(Transform parent, HashSet<Transform> chainBones,
|
||||
Dictionary<Transform, int> indexes, int fallback)
|
||||
{
|
||||
Transform current = parent;
|
||||
while (current != null && chainBones.Contains(current))
|
||||
{
|
||||
if (indexes.TryGetValue(current, out int index)) return index;
|
||||
current = current.parent;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
internal static Transform FindNearestExportedParentTransform(Transform parent,
|
||||
Dictionary<Transform, int> boneIndexes)
|
||||
{
|
||||
for (Transform current = parent; current != null; current = current.parent)
|
||||
if (boneIndexes.ContainsKey(current)) return current;
|
||||
return null;
|
||||
}
|
||||
|
||||
private static int GetDepth(Transform transform)
|
||||
{
|
||||
int depth = 0;
|
||||
for (Transform current = transform; current != null; current = current.parent) depth++;
|
||||
return depth;
|
||||
}
|
||||
|
||||
internal static float SanitizeRadius(float radius)
|
||||
{
|
||||
return IsFinite(radius) && radius > 0 ? Mathf.Clamp(radius, MinimumRadius, MaximumRadius) : DefaultRadius;
|
||||
}
|
||||
|
||||
private static bool IsLinearPhysicsElement(CySpringDataContainer container, CySpringParamDataElement element)
|
||||
{
|
||||
if (container == null || element == null) return false;
|
||||
|
||||
string boneText = (element._boneName ?? string.Empty).ToLowerInvariant();
|
||||
if (element._childElements != null)
|
||||
{
|
||||
foreach (CySpringParamDataChildElement child in element._childElements)
|
||||
if (child != null) boneText += " " + (child._boneName ?? string.Empty).ToLowerInvariant();
|
||||
}
|
||||
|
||||
// 排除裙摆与胸部/披风/袖子
|
||||
if (ContainsAny(boneText, "skirt", "cloth", "dress", "bust", "breast", "mune", "sleeve", "cape", "mskirt"))
|
||||
return false;
|
||||
|
||||
// 匹配头发、耳朵、马尾、呆毛及尾巴
|
||||
if (ContainsAny(boneText, "sp_he_", "sp_hi_tail", "hair", "ear", "tail", "head", "mimi", "shippo", "ponytail", "twin", "ahoge", "bang", "side", "back", "front"))
|
||||
return true;
|
||||
|
||||
string path = GetTransformPath(container.transform).ToLowerInvariant();
|
||||
if (ContainsAny(path, "skirt", "cloth", "dress", "bust", "breast", "mune", "sleeve", "cape", "mskirt"))
|
||||
return false;
|
||||
return ContainsAny(path, "sp_he_", "head", "hair", "ear", "tail", "mimi", "shippo");
|
||||
}
|
||||
|
||||
private static string GetTransformPath(Transform transform)
|
||||
{
|
||||
string path = string.Empty;
|
||||
for (Transform current = transform; current != null; current = current.parent)
|
||||
path = current.name + "/" + path;
|
||||
return path;
|
||||
}
|
||||
|
||||
private static bool ContainsAny(string text, params string[] values)
|
||||
{
|
||||
return values.Any(value => text.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0);
|
||||
}
|
||||
|
||||
private static void Validate(List<MMDRigidBody> rigidBodies, List<MMDJoint> joints, int boneCount)
|
||||
{
|
||||
for (int i = 0; i < rigidBodies.Count; i++)
|
||||
{
|
||||
MMDRigidBody body = rigidBodies[i];
|
||||
if (body.AssociatedBoneIndex < 0 || body.AssociatedBoneIndex >= boneCount)
|
||||
throw new InvalidOperationException("PMX 刚体骨骼索引无效: " + body.Name);
|
||||
if (body.CollisionGroup < 0 || body.CollisionGroup > 15)
|
||||
throw new InvalidOperationException("PMX 刚体碰撞组无效: " + body.Name);
|
||||
if (body.Type != MMDRigidBody.RigidBodyType.RigidTypeKinematic &&
|
||||
body.Type != MMDRigidBody.RigidBodyType.RigidTypePhysics &&
|
||||
body.Type != MMDRigidBody.RigidBodyType.RigidTypePhysicsStrict)
|
||||
throw new InvalidOperationException("PMX 导出不允许 Type 3 刚体: " + body.Name);
|
||||
if (!IsFinite(body.Position) || !IsFinite(body.Rotation) || !IsFinite(body.Dimemsions))
|
||||
throw new InvalidOperationException("PMX 刚体包含 NaN 或 Infinity: " + body.Name);
|
||||
if (body.Dimemsions.x <= 0f ||
|
||||
(body.Shape != MMDRigidBody.RigidBodyShape.RigidShapeSphere && body.Dimemsions.y <= 0f) ||
|
||||
(body.Shape == MMDRigidBody.RigidBodyShape.RigidShapeBox && body.Dimemsions.z <= 0f))
|
||||
throw new InvalidOperationException("PMX 刚体尺寸无效: " + body.Name);
|
||||
}
|
||||
|
||||
foreach (MMDJoint joint in joints)
|
||||
{
|
||||
int a = joint.AssociatedRigidBodyIndex[0];
|
||||
int b = joint.AssociatedRigidBodyIndex[1];
|
||||
if (a < 0 || a >= rigidBodies.Count || b < 0 || b >= rigidBodies.Count)
|
||||
throw new InvalidOperationException("PMX Joint 刚体索引无效: " + joint.Name);
|
||||
if (rigidBodies[a].Type == MMDRigidBody.RigidBodyType.RigidTypeKinematic &&
|
||||
rigidBodies[b].Type == MMDRigidBody.RigidBodyType.RigidTypeKinematic)
|
||||
throw new InvalidOperationException("PMX Joint 不能连接两个 Type 0 刚体: " + joint.Name);
|
||||
if (!IsFinite(joint.Position) || !IsFinite(joint.Rotation) ||
|
||||
!IsFinite(joint.PositionLowLimit) || !IsFinite(joint.PositionHiLimit) ||
|
||||
!IsFinite(joint.RotationLowLimit) || !IsFinite(joint.RotationHiLimit) ||
|
||||
!IsFinite(joint.SpringTranslate) || !IsFinite(joint.SpringRotate))
|
||||
throw new InvalidOperationException("PMX Joint 包含 NaN 或 Infinity: " + joint.Name);
|
||||
if (joint.PositionLowLimit.x > joint.PositionHiLimit.x ||
|
||||
joint.PositionLowLimit.y > joint.PositionHiLimit.y ||
|
||||
joint.PositionLowLimit.z > joint.PositionHiLimit.z)
|
||||
throw new InvalidOperationException("PMX Joint 平移上下限倒置: " + joint.Name);
|
||||
if (joint.RotationLowLimit.x > joint.RotationHiLimit.x ||
|
||||
joint.RotationLowLimit.y > joint.RotationHiLimit.y ||
|
||||
joint.RotationLowLimit.z > joint.RotationHiLimit.z)
|
||||
throw new InvalidOperationException("PMX Joint 旋转上下限倒置: " + joint.Name);
|
||||
}
|
||||
}
|
||||
|
||||
internal static bool IsFinite(float value)
|
||||
{
|
||||
return !float.IsNaN(value) && !float.IsInfinity(value);
|
||||
}
|
||||
|
||||
private static bool IsFinite(Vector3 value)
|
||||
{
|
||||
return IsFinite(value.x) && IsFinite(value.y) && IsFinite(value.z);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 82a6d87d563d4a08a24aca4ed09629cc
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,487 @@
|
||||
using Gallop;
|
||||
using LibMMD.Model;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// 负责将 SkirtController 与裙摆骨骼网格转换为 PMX 2.0 盒体刚体与约束 Joint。
|
||||
/// </summary>
|
||||
internal static class PMXSkirtPhysicsExporter
|
||||
{
|
||||
private const float SkirtMinimumPanelHalfWidth = 0.012f;
|
||||
private const float SkirtMaximumPanelHalfWidth = 0.08f;
|
||||
private const float SkirtMinimumPanelHalfThickness = 0.004f;
|
||||
private const float SkirtMaximumPanelHalfThickness = 0.016f;
|
||||
private const float SkirtVerticalBendDegrees = 16f;
|
||||
private const float SkirtVerticalTwistDegrees = 6f;
|
||||
private const float SkirtLegColliderRadiusScale = 0.15f;
|
||||
|
||||
// 裙摆段临时信息
|
||||
internal sealed class SkirtSegment
|
||||
{
|
||||
internal Transform Bone;
|
||||
internal Transform Child;
|
||||
internal int ColumnIndex;
|
||||
internal int RowIndex;
|
||||
internal int RigidIndex;
|
||||
internal Vector3 Start;
|
||||
internal Vector3 End;
|
||||
internal Vector3 Center;
|
||||
internal Vector3 Rotation;
|
||||
internal float Length;
|
||||
internal float HalfWidth;
|
||||
internal float HalfThickness;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 收集角色裙摆列链。
|
||||
/// </summary>
|
||||
internal static void CollectSkirtColumns(UmaContainerCharacter character, Transform skeletonRoot,
|
||||
PMXPhysicsExporter.Context context, HashSet<Transform> claimedBones)
|
||||
{
|
||||
SkirtController controller = context.SkirtController;
|
||||
if (controller == null || controller.SkirtDataArray == null) return;
|
||||
|
||||
foreach (SkirtController.SkirtData skirtData in controller.SkirtDataArray)
|
||||
{
|
||||
if (skirtData == null || skirtData.SkirtRoot == null || skirtData.SkirtChild == null) continue;
|
||||
if (skirtData.SkirtRoot != skeletonRoot && !skirtData.SkirtRoot.IsChildOf(skeletonRoot)) continue;
|
||||
if (claimedBones.Contains(skirtData.SkirtRoot)) continue;
|
||||
|
||||
PMXPhysicsExporter.Chain bestChain = null;
|
||||
foreach (CySpringDataContainer container in character.cySpringDataContainers)
|
||||
{
|
||||
if (container == null || container.springParam == null) continue;
|
||||
foreach (CySpringParamDataElement element in container.springParam)
|
||||
{
|
||||
if (element == null || !string.Equals(
|
||||
element._boneName, skirtData.SkirtRoot.name, StringComparison.Ordinal)) continue;
|
||||
|
||||
PMXPhysicsExporter.Chain candidate = BuildChainFromRoot(element, skirtData.SkirtRoot);
|
||||
if (candidate == null || !candidate.Bones.Contains(skirtData.SkirtChild) ||
|
||||
!IsStrictLinearChain(candidate, skirtData.SkirtChild)) continue;
|
||||
if (bestChain == null || candidate.Bones.Count > bestChain.Bones.Count) bestChain = candidate;
|
||||
}
|
||||
}
|
||||
|
||||
if (bestChain == null) continue;
|
||||
claimedBones.UnionWith(bestChain.Bones);
|
||||
context.SkirtColumns.Add(new PMXPhysicsExporter.SkirtColumn
|
||||
{
|
||||
Chain = bestChain,
|
||||
IsCheckRightLeg = skirtData.IsCheckRightLeg,
|
||||
IsCheckLeftLeg = skirtData.IsCheckLeftLeg
|
||||
});
|
||||
|
||||
foreach (Transform bone in bestChain.Bones)
|
||||
{
|
||||
// 裙摆骨骼即使无蒙皮权重,也决定物理链完整性
|
||||
context.DynamicBones.Add(bone);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 构建裙摆刚体、Joint 与腿部碰撞体。
|
||||
/// </summary>
|
||||
internal static void BuildSkirtPhysics(PMXPhysicsExporter.Context context, Transform coordinateRoot,
|
||||
PMXBoneExporter.Result boneResult, List<MMDRigidBody> rigidBodies, List<MMDJoint> joints,
|
||||
Dictionary<Transform, int> dynamicRigidIndexes)
|
||||
{
|
||||
if (context.SkirtController == null || context.SkirtColumns.Count < 3) return;
|
||||
|
||||
List<PMXPhysicsExporter.SkirtColumn> columns = OrderSkirtColumns(context.SkirtColumns, context.SkirtController, coordinateRoot);
|
||||
List<List<SkirtSegment>> segmentsByColumn = new List<List<SkirtSegment>>();
|
||||
for (int columnIndex = 0; columnIndex < columns.Count; columnIndex++)
|
||||
{
|
||||
List<Transform> bones = GetOrderedLinearBones(columns[columnIndex].Chain);
|
||||
List<SkirtSegment> segments = new List<SkirtSegment>();
|
||||
for (int rowIndex = 0; rowIndex + 1 < bones.Count; rowIndex++)
|
||||
{
|
||||
Transform bone = bones[rowIndex];
|
||||
Transform child = bones[rowIndex + 1];
|
||||
if (!boneResult.BoneIndexes.ContainsKey(bone)) break;
|
||||
|
||||
Vector3 start = coordinateRoot.InverseTransformPoint(bone.position);
|
||||
Vector3 end = coordinateRoot.InverseTransformPoint(child.position);
|
||||
float length = Vector3.Distance(start, end);
|
||||
if (!PMXPhysicsExporter.IsFinite(length) || length <= PMXPhysicsExporter.MinimumSegmentLength) break;
|
||||
|
||||
segments.Add(new SkirtSegment
|
||||
{
|
||||
Bone = bone,
|
||||
Child = child,
|
||||
ColumnIndex = columnIndex,
|
||||
RowIndex = rowIndex,
|
||||
Start = start,
|
||||
End = end,
|
||||
Center = (start + end) * 0.5f,
|
||||
Length = length,
|
||||
RigidIndex = -1
|
||||
});
|
||||
}
|
||||
segmentsByColumn.Add(segments);
|
||||
}
|
||||
|
||||
// 少于三列或任意列没有有效首段时无法建立稳定的裙摆网格
|
||||
if (segmentsByColumn.Count < 3 || segmentsByColumn.Any(segments => segments.Count == 0)) return;
|
||||
|
||||
bool closeRing = IsClosedSkirtRing(columns, context.SkirtController, coordinateRoot);
|
||||
for (int columnIndex = 0; columnIndex < columns.Count; columnIndex++)
|
||||
{
|
||||
List<SkirtSegment> segments = segmentsByColumn[columnIndex];
|
||||
for (int rowIndex = 0; rowIndex < segments.Count; rowIndex++)
|
||||
{
|
||||
SkirtSegment segment = segments[rowIndex];
|
||||
Vector3 tangent = CalculateSkirtTangent(segmentsByColumn, columnIndex, rowIndex, closeRing);
|
||||
segment.HalfWidth = EstimateSkirtPanelHalfWidth(
|
||||
segmentsByColumn, columnIndex, rowIndex, closeRing);
|
||||
float configuredRadius = columns[columnIndex].Chain.Radii[segment.Bone];
|
||||
segment.HalfThickness = Mathf.Clamp(
|
||||
configuredRadius * 0.55f,
|
||||
SkirtMinimumPanelHalfThickness,
|
||||
SkirtMaximumPanelHalfThickness);
|
||||
segment.Rotation = CalculatePanelRotation(segment.End - segment.Start, tangent);
|
||||
}
|
||||
}
|
||||
|
||||
for (int columnIndex = 0; columnIndex < columns.Count; columnIndex++)
|
||||
{
|
||||
PMXPhysicsExporter.SkirtColumn column = columns[columnIndex];
|
||||
List<SkirtSegment> segments = segmentsByColumn[columnIndex];
|
||||
Transform anchorBone = PMXPhysicsExporter.FindNearestExportedParentTransform(column.Chain.Root.parent, boneResult.BoneIndexes);
|
||||
int anchorBoneIndex = anchorBone != null ? boneResult.BoneIndexes[anchorBone] : 0;
|
||||
int parentRigidIndex = rigidBodies.Count;
|
||||
Vector3 anchorRotation = segments.Count > 0 ? segments[0].Rotation : Vector3.zero;
|
||||
rigidBodies.Add(CreateSkirtAnchorBody(column, coordinateRoot, anchorBoneIndex, anchorRotation));
|
||||
|
||||
for (int rowIndex = 0; rowIndex < segments.Count; rowIndex++)
|
||||
{
|
||||
SkirtSegment segment = segments[rowIndex];
|
||||
float depthRatio = segments.Count > 1 ? rowIndex / (float)(segments.Count - 1) : 0f;
|
||||
int boneIndex = boneResult.BoneIndexes[segment.Bone];
|
||||
segment.RigidIndex = rigidBodies.Count;
|
||||
rigidBodies.Add(CreateSkirtPanelBody(segment, boneIndex, depthRatio));
|
||||
dynamicRigidIndexes[segment.Bone] = segment.RigidIndex;
|
||||
joints.Add(CreateSkirtVerticalJoint(segment, parentRigidIndex, depthRatio));
|
||||
parentRigidIndex = segment.RigidIndex;
|
||||
}
|
||||
}
|
||||
|
||||
AddSkirtLegColliders(
|
||||
context.SkirtController, columns, coordinateRoot, boneResult.BoneIndexes, rigidBodies);
|
||||
}
|
||||
|
||||
private static PMXPhysicsExporter.Chain BuildChainFromRoot(CySpringParamDataElement element, Transform root)
|
||||
{
|
||||
if (element == null || root == null ||
|
||||
!string.Equals(element._boneName, root.name, StringComparison.Ordinal)) return null;
|
||||
|
||||
Dictionary<string, float> configuredBones = new Dictionary<string, float>(StringComparer.Ordinal)
|
||||
{
|
||||
[element._boneName] = PMXPhysicsExporter.SanitizeRadius(element._collisionRadius)
|
||||
};
|
||||
if (element._childElements != null)
|
||||
{
|
||||
foreach (CySpringParamDataChildElement child in element._childElements)
|
||||
{
|
||||
if (child != null && !string.IsNullOrEmpty(child._boneName))
|
||||
configuredBones[child._boneName] = PMXPhysicsExporter.SanitizeRadius(child._collisionRadius);
|
||||
}
|
||||
}
|
||||
|
||||
PMXPhysicsExporter.Chain chain = new PMXPhysicsExporter.Chain { Root = root };
|
||||
PMXPhysicsExporter.CollectContinuousBones(root, configuredBones, chain);
|
||||
return chain.Bones.Count > 0 ? chain : null;
|
||||
}
|
||||
|
||||
private static bool IsStrictLinearChain(PMXPhysicsExporter.Chain chain, Transform expectedFirstChild)
|
||||
{
|
||||
if (chain == null || chain.Root == null || expectedFirstChild == null) return false;
|
||||
|
||||
Transform current = chain.Root;
|
||||
int visited = 0;
|
||||
bool foundExpectedChild = false;
|
||||
while (current != null && chain.Bones.Contains(current))
|
||||
{
|
||||
visited++;
|
||||
Transform next = PMXPhysicsExporter.GetSingleChainChild(current, chain.Bones);
|
||||
if (current == chain.Root) foundExpectedChild = next == expectedFirstChild;
|
||||
if (next == null) break;
|
||||
current = next;
|
||||
}
|
||||
return foundExpectedChild && visited == chain.Bones.Count && visited >= 2;
|
||||
}
|
||||
|
||||
private static List<Transform> GetOrderedLinearBones(PMXPhysicsExporter.Chain chain)
|
||||
{
|
||||
List<Transform> result = new List<Transform>();
|
||||
Transform current = chain.Root;
|
||||
while (current != null && chain.Bones.Contains(current))
|
||||
{
|
||||
result.Add(current);
|
||||
current = PMXPhysicsExporter.GetSingleChainChild(current, chain.Bones);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static List<PMXPhysicsExporter.SkirtColumn> OrderSkirtColumns(IEnumerable<PMXPhysicsExporter.SkirtColumn> columns,
|
||||
SkirtController controller, Transform coordinateRoot)
|
||||
{
|
||||
List<PMXPhysicsExporter.SkirtColumn> result = columns.ToList();
|
||||
Vector3 center = controller.CenterBone != null
|
||||
? coordinateRoot.InverseTransformPoint(controller.CenterBone.position)
|
||||
: result.Aggregate(Vector3.zero, (sum, column) =>
|
||||
sum + coordinateRoot.InverseTransformPoint(column.Chain.Root.position)) / result.Count;
|
||||
|
||||
return result.OrderBy(column =>
|
||||
{
|
||||
Vector3 position = coordinateRoot.InverseTransformPoint(column.Chain.Root.position) - center;
|
||||
return Mathf.Atan2(position.z, position.x);
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
private static bool IsClosedSkirtRing(IList<PMXPhysicsExporter.SkirtColumn> columns, SkirtController controller,
|
||||
Transform coordinateRoot)
|
||||
{
|
||||
if (columns.Count < 3) return false;
|
||||
Vector3 center = controller.CenterBone != null
|
||||
? coordinateRoot.InverseTransformPoint(controller.CenterBone.position)
|
||||
: columns.Aggregate(Vector3.zero, (sum, column) =>
|
||||
sum + coordinateRoot.InverseTransformPoint(column.Chain.Root.position)) / columns.Count;
|
||||
List<float> angles = columns.Select(column =>
|
||||
{
|
||||
Vector3 position = coordinateRoot.InverseTransformPoint(column.Chain.Root.position) - center;
|
||||
return Mathf.Atan2(position.z, position.x);
|
||||
}).OrderBy(angle => angle).ToList();
|
||||
|
||||
float maximumGap = 0f;
|
||||
for (int i = 0; i < angles.Count; i++)
|
||||
{
|
||||
float next = i + 1 < angles.Count ? angles[i + 1] : angles[0] + Mathf.PI * 2f;
|
||||
maximumGap = Mathf.Max(maximumGap, next - angles[i]);
|
||||
}
|
||||
float averageGap = Mathf.PI * 2f / angles.Count;
|
||||
return maximumGap <= Mathf.Min(averageGap * 2.25f, 150f * Mathf.Deg2Rad);
|
||||
}
|
||||
|
||||
private static Vector3 CalculateSkirtTangent(IList<List<SkirtSegment>> columns,
|
||||
int columnIndex, int rowIndex, bool closeRing)
|
||||
{
|
||||
SkirtSegment current = columns[columnIndex][rowIndex];
|
||||
SkirtSegment previous = GetNeighborSkirtSegment(columns, columnIndex - 1, rowIndex, closeRing);
|
||||
SkirtSegment next = GetNeighborSkirtSegment(columns, columnIndex + 1, rowIndex, closeRing);
|
||||
if (previous != null && next != null) return next.Center - previous.Center;
|
||||
if (next != null) return next.Center - current.Center;
|
||||
if (previous != null) return current.Center - previous.Center;
|
||||
return Vector3.right;
|
||||
}
|
||||
|
||||
private static float EstimateSkirtPanelHalfWidth(IList<List<SkirtSegment>> columns,
|
||||
int columnIndex, int rowIndex, bool closeRing)
|
||||
{
|
||||
SkirtSegment current = columns[columnIndex][rowIndex];
|
||||
SkirtSegment previous = GetNeighborSkirtSegment(columns, columnIndex - 1, rowIndex, closeRing);
|
||||
SkirtSegment next = GetNeighborSkirtSegment(columns, columnIndex + 1, rowIndex, closeRing);
|
||||
float spacing = 0f;
|
||||
int sampleCount = 0;
|
||||
if (previous != null)
|
||||
{
|
||||
spacing += Vector3.Distance(current.Center, previous.Center);
|
||||
sampleCount++;
|
||||
}
|
||||
if (next != null)
|
||||
{
|
||||
spacing += Vector3.Distance(current.Center, next.Center);
|
||||
sampleCount++;
|
||||
}
|
||||
if (sampleCount == 0) return SkirtMinimumPanelHalfWidth;
|
||||
return Mathf.Clamp(spacing / sampleCount * 0.48f,
|
||||
SkirtMinimumPanelHalfWidth, SkirtMaximumPanelHalfWidth);
|
||||
}
|
||||
|
||||
private static SkirtSegment GetNeighborSkirtSegment(IList<List<SkirtSegment>> columns,
|
||||
int columnIndex, int rowIndex, bool closeRing)
|
||||
{
|
||||
if (closeRing)
|
||||
{
|
||||
columnIndex %= columns.Count;
|
||||
if (columnIndex < 0) columnIndex += columns.Count;
|
||||
}
|
||||
else if (columnIndex < 0 || columnIndex >= columns.Count)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
List<SkirtSegment> segments = columns[columnIndex];
|
||||
return rowIndex >= 0 && rowIndex < segments.Count ? segments[rowIndex] : null;
|
||||
}
|
||||
|
||||
private static Vector3 CalculatePanelRotation(Vector3 segmentDirection, Vector3 tangentDirection)
|
||||
{
|
||||
Vector3 up = segmentDirection.normalized;
|
||||
Vector3 right = Vector3.ProjectOnPlane(tangentDirection, up);
|
||||
if (right.sqrMagnitude < PMXPhysicsExporter.MinimumSegmentLength * PMXPhysicsExporter.MinimumSegmentLength)
|
||||
right = Vector3.ProjectOnPlane(Vector3.right, up);
|
||||
if (right.sqrMagnitude < PMXPhysicsExporter.MinimumSegmentLength * PMXPhysicsExporter.MinimumSegmentLength)
|
||||
right = Vector3.ProjectOnPlane(Vector3.forward, up);
|
||||
right.Normalize();
|
||||
Vector3 forward = Vector3.Cross(right, up).normalized;
|
||||
right = Vector3.Cross(up, forward).normalized;
|
||||
return PMXPhysicsExporter.ConvertUnityRotationToWriterEuler(Quaternion.LookRotation(forward, up));
|
||||
}
|
||||
|
||||
private static MMDRigidBody CreateSkirtAnchorBody(PMXPhysicsExporter.SkirtColumn column,
|
||||
Transform coordinateRoot, int boneIndex, Vector3 rotation)
|
||||
{
|
||||
float radius = Mathf.Max(PMXPhysicsExporter.MinimumRadius, column.Chain.Radii[column.Chain.Root] * 0.5f);
|
||||
return new MMDRigidBody
|
||||
{
|
||||
Name = column.Chain.Root.name + "_skirt_anchor",
|
||||
NameEn = column.Chain.Root.name + "_skirt_anchor",
|
||||
AssociatedBoneIndex = boneIndex,
|
||||
CollisionGroup = PMXPhysicsExporter.SkirtCollisionGroup,
|
||||
CollisionMask = PMXPhysicsExporter.CreateCollisionMaskExcludingGroups(
|
||||
PMXPhysicsExporter.SkirtCollisionGroup, PMXPhysicsExporter.DynamicCollisionGroup, PMXPhysicsExporter.TailBodyCollisionGroup),
|
||||
Shape = MMDRigidBody.RigidBodyShape.RigidShapeSphere,
|
||||
Dimemsions = new Vector3(radius, 0, 0),
|
||||
Position = coordinateRoot.InverseTransformPoint(column.Chain.Root.position),
|
||||
Rotation = rotation,
|
||||
Mass = 0,
|
||||
TranslateDamp = 1,
|
||||
RotateDamp = 1,
|
||||
Restitution = 0,
|
||||
Friction = 0,
|
||||
Type = MMDRigidBody.RigidBodyType.RigidTypeKinematic
|
||||
};
|
||||
}
|
||||
|
||||
private static MMDRigidBody CreateSkirtPanelBody(SkirtSegment segment, int boneIndex,
|
||||
float depthRatio)
|
||||
{
|
||||
return new MMDRigidBody
|
||||
{
|
||||
Name = segment.Bone.name + "_skirt_physics",
|
||||
NameEn = segment.Bone.name + "_skirt_physics",
|
||||
AssociatedBoneIndex = boneIndex,
|
||||
CollisionGroup = PMXPhysicsExporter.SkirtCollisionGroup,
|
||||
CollisionMask = PMXPhysicsExporter.CreateCollisionMaskExcludingGroups(
|
||||
PMXPhysicsExporter.SkirtCollisionGroup, PMXPhysicsExporter.DynamicCollisionGroup, PMXPhysicsExporter.TailBodyCollisionGroup),
|
||||
Shape = MMDRigidBody.RigidBodyShape.RigidShapeBox,
|
||||
Dimemsions = new Vector3(
|
||||
segment.HalfWidth, segment.Length * 0.46f, segment.HalfThickness),
|
||||
Position = segment.Center,
|
||||
Rotation = segment.Rotation,
|
||||
Mass = Mathf.Lerp(PMXPhysicsExporter.SkirtPreset.RootMass, PMXPhysicsExporter.SkirtPreset.TipMass, depthRatio),
|
||||
TranslateDamp = Mathf.Lerp(
|
||||
PMXPhysicsExporter.SkirtPreset.RootTranslateDamp, PMXPhysicsExporter.SkirtPreset.TipTranslateDamp, depthRatio),
|
||||
RotateDamp = Mathf.Lerp(
|
||||
PMXPhysicsExporter.SkirtPreset.RootRotateDamp, PMXPhysicsExporter.SkirtPreset.TipRotateDamp, depthRatio),
|
||||
Restitution = 0,
|
||||
Friction = 0,
|
||||
Type = MMDRigidBody.RigidBodyType.RigidTypePhysics
|
||||
};
|
||||
}
|
||||
|
||||
private static MMDJoint CreateSkirtVerticalJoint(SkirtSegment segment,
|
||||
int parentRigidIndex, float depthRatio)
|
||||
{
|
||||
float bend = SkirtVerticalBendDegrees * Mathf.Deg2Rad;
|
||||
float twist = SkirtVerticalTwistDegrees * Mathf.Deg2Rad;
|
||||
float bendSpring = Mathf.Lerp(
|
||||
PMXPhysicsExporter.SkirtPreset.BendSpring, PMXPhysicsExporter.SkirtPreset.BendSpring * 0.5f, depthRatio);
|
||||
float twistSpring = Mathf.Lerp(
|
||||
PMXPhysicsExporter.SkirtPreset.TwistSpring, PMXPhysicsExporter.SkirtPreset.TwistSpring * 0.5f, depthRatio);
|
||||
return new MMDJoint
|
||||
{
|
||||
Name = segment.Bone.name + "_skirt_vertical_joint",
|
||||
NameEn = segment.Bone.name + "_skirt_vertical_joint",
|
||||
AssociatedRigidBodyIndex = new[] { parentRigidIndex, segment.RigidIndex },
|
||||
Position = segment.Start,
|
||||
Rotation = segment.Rotation,
|
||||
PositionLowLimit = Vector3.zero,
|
||||
PositionHiLimit = Vector3.zero,
|
||||
RotationLowLimit = new Vector3(-bend, -twist, -bend * 0.75f),
|
||||
RotationHiLimit = new Vector3(bend, twist, bend * 0.75f),
|
||||
SpringTranslate = Vector3.zero,
|
||||
SpringRotate = new Vector3(bendSpring, twistSpring, bendSpring)
|
||||
};
|
||||
}
|
||||
|
||||
private static void AddSkirtLegColliders(SkirtController controller,
|
||||
IEnumerable<PMXPhysicsExporter.SkirtColumn> columns, Transform coordinateRoot,
|
||||
Dictionary<Transform, int> boneIndexes, List<MMDRigidBody> rigidBodies)
|
||||
{
|
||||
bool checkLeft = columns.Any(column => column.IsCheckLeftLeg);
|
||||
bool checkRight = columns.Any(column => column.IsCheckRightLeg);
|
||||
float kneeRadius = SanitizeSkirtColliderRadius(
|
||||
controller.KneeColliderRadius * SkirtLegColliderRadiusScale, 0.044f);
|
||||
float ankleRadius = SanitizeSkirtColliderRadius(
|
||||
controller.AnkleColliderRadius * SkirtLegColliderRadiusScale, 0.036f);
|
||||
if (checkLeft) AddLegColliderChain(
|
||||
"left", controller.KneeLBone, controller.AnkleLBone, kneeRadius, ankleRadius,
|
||||
coordinateRoot, boneIndexes, rigidBodies);
|
||||
if (checkRight) AddLegColliderChain(
|
||||
"right", controller.KneeRBone, controller.AnkleRBone, kneeRadius, ankleRadius,
|
||||
coordinateRoot, boneIndexes, rigidBodies);
|
||||
}
|
||||
|
||||
private static void AddLegColliderChain(string side, Transform knee, Transform ankle,
|
||||
float kneeRadius, float ankleRadius, Transform coordinateRoot,
|
||||
Dictionary<Transform, int> boneIndexes, List<MMDRigidBody> rigidBodies)
|
||||
{
|
||||
if (knee == null || !boneIndexes.ContainsKey(knee)) return;
|
||||
Transform thigh = PMXPhysicsExporter.FindNearestExportedParentTransform(knee.parent, boneIndexes);
|
||||
if (thigh != null)
|
||||
AddKinematicCapsule(side + "_thigh_skirt_collider", thigh, knee, kneeRadius,
|
||||
coordinateRoot, boneIndexes, rigidBodies);
|
||||
if (ankle != null && boneIndexes.ContainsKey(ankle))
|
||||
AddKinematicCapsule(side + "_shin_skirt_collider", knee, ankle,
|
||||
(kneeRadius + ankleRadius) * 0.5f, coordinateRoot, boneIndexes, rigidBodies);
|
||||
}
|
||||
|
||||
private static void AddKinematicCapsule(string name, Transform startBone, Transform endBone,
|
||||
float radius, Transform coordinateRoot, Dictionary<Transform, int> boneIndexes,
|
||||
List<MMDRigidBody> rigidBodies)
|
||||
{
|
||||
if (startBone == null || endBone == null || !boneIndexes.TryGetValue(startBone, out int boneIndex)) return;
|
||||
Vector3 start = coordinateRoot.InverseTransformPoint(startBone.position);
|
||||
Vector3 end = coordinateRoot.InverseTransformPoint(endBone.position);
|
||||
float length = Vector3.Distance(start, end);
|
||||
if (length <= PMXPhysicsExporter.MinimumSegmentLength) return;
|
||||
|
||||
// 计算腿部胶囊体旋转与中心
|
||||
Quaternion boneRot = Quaternion.Inverse(coordinateRoot.rotation) * startBone.rotation;
|
||||
Vector3 localDelta = startBone.InverseTransformPoint(endBone.position);
|
||||
Vector3 localDir = localDelta.sqrMagnitude > 0.000001f ? localDelta.normalized : Vector3.down;
|
||||
Quaternion capsuleRot = boneRot * Quaternion.FromToRotation(Vector3.up, localDir);
|
||||
|
||||
rigidBodies.Add(new MMDRigidBody
|
||||
{
|
||||
Name = name,
|
||||
NameEn = name,
|
||||
AssociatedBoneIndex = boneIndex,
|
||||
CollisionGroup = PMXPhysicsExporter.SkirtLegCollisionGroup,
|
||||
CollisionMask = PMXPhysicsExporter.CreateCollisionMaskExcludingGroups(
|
||||
PMXPhysicsExporter.SkirtLegCollisionGroup, PMXPhysicsExporter.DynamicCollisionGroup, PMXPhysicsExporter.TailBodyCollisionGroup),
|
||||
Shape = MMDRigidBody.RigidBodyShape.RigidShapeCapsule,
|
||||
Dimemsions = new Vector3(radius, PMXPhysicsExporter.GetCapsuleCylinderLength(length, radius), 0),
|
||||
Position = (start + end) * 0.5f,
|
||||
Rotation = PMXPhysicsExporter.ConvertUnityRotationToWriterEuler(capsuleRot),
|
||||
Mass = 0,
|
||||
TranslateDamp = 1,
|
||||
RotateDamp = 1,
|
||||
Restitution = 0,
|
||||
Friction = 0,
|
||||
Type = MMDRigidBody.RigidBodyType.RigidTypeKinematic
|
||||
});
|
||||
}
|
||||
|
||||
private static float SanitizeSkirtColliderRadius(float radius, float fallback)
|
||||
{
|
||||
float value = PMXPhysicsExporter.IsFinite(radius) && radius > 0f ? radius : fallback;
|
||||
return Mathf.Clamp(value, 0.01f, 0.04f);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: bf787d53ff0b46b40b84ba2d590d9377
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -9,13 +9,7 @@ public class TextureExporter
|
||||
{
|
||||
static public Texture2D duplicateTexture(Texture2D source)
|
||||
{
|
||||
RenderTexture renderTex = RenderTexture.GetTemporary(
|
||||
source.width,
|
||||
source.height,
|
||||
0,
|
||||
RenderTextureFormat.Default,
|
||||
RenderTextureReadWrite.Linear);
|
||||
|
||||
RenderTexture renderTex = RenderTexture.GetTemporary(source.width, source.height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Linear);
|
||||
Graphics.Blit(source, renderTex);
|
||||
RenderTexture previous = RenderTexture.active;
|
||||
RenderTexture.active = renderTex;
|
||||
@@ -40,7 +34,7 @@ public class TextureExporter
|
||||
{
|
||||
foreach (Material mat in renderer.sharedMaterials)
|
||||
{
|
||||
//»ñµÃ²ÄÖʵÄËùÓÐÊôÐÔÃû£¬Èç¹û¸ÄÊôÐÔÃû¶ÔÓ¦µÄÊÇÌùͼ£¬ÌáÈ¡¸ÃÌùͼ
|
||||
// 获取材质的所有属性;如果某个属性对应纹理,则提取该纹理
|
||||
Shader mat_shader = mat.shader;
|
||||
int p_num = mat_shader.GetPropertyCount();
|
||||
for (int i = 0; i < p_num; i++)
|
||||
@@ -85,7 +79,7 @@ public class TextureExporter
|
||||
}
|
||||
}
|
||||
}
|
||||
Debug.Log("ÌáÈ¡³É¹¦");
|
||||
Debug.Log("纹理提取成功。");
|
||||
return textureNames.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,13 +66,17 @@ namespace LibMMD.Reader
|
||||
joint.AssociatedRigidBodyIndex[1] =
|
||||
MMDReaderWriteUtil.ReadIndex(reader, pmxConfig.RigidBodyIndexSize);
|
||||
joint.Position = MMDReaderWriteUtil.ReadVector3(reader);
|
||||
joint.Rotation = MMDReaderWriteUtil.ReadAmpVector3(reader, Mathf.Rad2Deg);
|
||||
joint.PositionLowLimit = MMDReaderWriteUtil.ReadVector3(reader);
|
||||
joint.PositionHiLimit = MMDReaderWriteUtil.ReadVector3(reader);
|
||||
joint.RotationLowLimit = MMDReaderWriteUtil.ReadVector3(reader);
|
||||
joint.RotationHiLimit = MMDReaderWriteUtil.ReadVector3(reader);
|
||||
joint.SpringTranslate = MMDReaderWriteUtil.ReadVector3(reader);
|
||||
joint.SpringRotate = MMDReaderWriteUtil.ReadVector3(reader);
|
||||
joint.Rotation = MMDReaderWriteUtil.ReadEulerRotation(reader);
|
||||
MMDReaderWriteUtil.ReadPositionLimitPair(
|
||||
reader, out Vector3 positionLowLimit, out Vector3 positionHiLimit);
|
||||
joint.PositionLowLimit = positionLowLimit;
|
||||
joint.PositionHiLimit = positionHiLimit;
|
||||
// PMX Joint 角限制和旋转弹簧按文件中的弧度分量原样读取。
|
||||
joint.RotationLowLimit = MMDReaderWriteUtil.ReadRawVector3(reader);
|
||||
joint.RotationHiLimit = MMDReaderWriteUtil.ReadRawVector3(reader);
|
||||
// 平移弹簧按 PMX 文件中的各轴刚度原样读取。
|
||||
joint.SpringTranslate = MMDReaderWriteUtil.ReadRawVector3(reader);
|
||||
joint.SpringRotate = MMDReaderWriteUtil.ReadRawVector3(reader);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -116,7 +120,7 @@ namespace LibMMD.Reader
|
||||
Shape = (MMDRigidBody.RigidBodyShape) reader.ReadByte(),
|
||||
Dimemsions = MMDReaderWriteUtil.ReadRawCoordinateVector3(reader),
|
||||
Position = MMDReaderWriteUtil.ReadVector3(reader),
|
||||
Rotation = MMDReaderWriteUtil.ReadAmpVector3(reader, Mathf.Rad2Deg),
|
||||
Rotation = MMDReaderWriteUtil.ReadEulerRotation(reader),
|
||||
Mass = reader.ReadSingle(),
|
||||
TranslateDamp = reader.ReadSingle(),
|
||||
RotateDamp = reader.ReadSingle(),
|
||||
@@ -363,8 +367,12 @@ namespace LibMMD.Reader
|
||||
link.HasLimit = reader.ReadByte() != 0;
|
||||
if (link.HasLimit)
|
||||
{
|
||||
link.LoLimit = MMDReaderWriteUtil.ReadVector3(reader);
|
||||
link.HiLimit = MMDReaderWriteUtil.ReadVector3(reader);
|
||||
// PMX IK 限制是文件坐标系下的原始弧度,运行时求解器负责角度坐标转换。
|
||||
Vector3 first = MMDReaderWriteUtil.ReadRawVector3(reader);
|
||||
Vector3 second = MMDReaderWriteUtil.ReadRawVector3(reader);
|
||||
// 对外部异常文件保持容错,同时确保内部区间始终满足 lower <= upper。
|
||||
link.LoLimit = Vector3.Min(first, second);
|
||||
link.HiLimit = Vector3.Max(first, second);
|
||||
}
|
||||
bone.IkInfoVal.IkLinks[j] = link;
|
||||
}
|
||||
@@ -625,4 +633,4 @@ namespace LibMMD.Reader
|
||||
public const ushort PmxBoneReceiveTransform = 0x2000;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,6 +121,66 @@ namespace LibMMD.Util
|
||||
writer.Write(-vector.z / amp);
|
||||
}
|
||||
|
||||
public static Vector3 ReadEulerRotation(BinaryReader reader)
|
||||
{
|
||||
// PMX/mmd_tools 使用 YXZ 欧拉模式;经过 X/Z 坐标取反后,它与
|
||||
// Unity Quaternion.Euler 的 ZXY 模式逐分量对应,不能再按 ZYX 重分解。
|
||||
return ReadAmpVector3(reader, Mathf.Rad2Deg);
|
||||
}
|
||||
|
||||
public static void WriteEulerRotation(BinaryWriter writer, Vector3 unityEulerDegrees)
|
||||
{
|
||||
// mmd_tools 导入时执行 PMX(x,y,z) -> Blender(-x,-z,-y),
|
||||
// 这里保持原始欧拉分量映射,避免复合旋转的局部轴被重新排列。
|
||||
WriteAmpVector3(writer, unityEulerDegrees, Mathf.Rad2Deg);
|
||||
}
|
||||
|
||||
public static void ReadPositionLimitPair(BinaryReader reader, out Vector3 lower, out Vector3 upper)
|
||||
{
|
||||
Vector3 pmxLower = ReadRawVector3(reader);
|
||||
Vector3 pmxUpper = ReadRawVector3(reader);
|
||||
|
||||
// X/Z 轴取反会反转区间方向,因此必须交叉读取对应的上下界。
|
||||
lower = new Vector3(
|
||||
-pmxUpper.x * WorldSizeAmplifier,
|
||||
pmxLower.y * WorldSizeAmplifier,
|
||||
-pmxUpper.z * WorldSizeAmplifier);
|
||||
upper = new Vector3(
|
||||
-pmxLower.x * WorldSizeAmplifier,
|
||||
pmxUpper.y * WorldSizeAmplifier,
|
||||
-pmxLower.z * WorldSizeAmplifier);
|
||||
}
|
||||
|
||||
public static void WritePositionLimitPair(BinaryWriter writer, Vector3 lower, Vector3 upper)
|
||||
{
|
||||
// PMX 仍使用模型尺寸单位;X/Z 轴取反后交换上下界以维持 lower <= upper。
|
||||
WriteRawVector3(writer, new Vector3(
|
||||
-upper.x / WorldSizeAmplifier,
|
||||
lower.y / WorldSizeAmplifier,
|
||||
-upper.z / WorldSizeAmplifier));
|
||||
WriteRawVector3(writer, new Vector3(
|
||||
-lower.x / WorldSizeAmplifier,
|
||||
upper.y / WorldSizeAmplifier,
|
||||
-lower.z / WorldSizeAmplifier));
|
||||
}
|
||||
|
||||
public static Vector3 ReadRawVector3(BinaryReader reader)
|
||||
{
|
||||
// IK 角度等非空间向量必须保留 PMX 文件中的原始分量和值域。
|
||||
return new Vector3(
|
||||
MathUtil.NanToZero(reader.ReadSingle()),
|
||||
MathUtil.NanToZero(reader.ReadSingle()),
|
||||
MathUtil.NanToZero(reader.ReadSingle()));
|
||||
}
|
||||
|
||||
public static void WriteRawVector3(BinaryWriter writer, Vector3 vector)
|
||||
{
|
||||
// 不应用模型尺寸倍率或 Unity/PMX 坐标轴翻转。
|
||||
writer.Write(vector.x);
|
||||
writer.Write(vector.y);
|
||||
writer.Write(vector.z);
|
||||
}
|
||||
|
||||
|
||||
public static Vector3 ReadRawCoordinateVector3(BinaryReader reader)
|
||||
{
|
||||
@@ -218,4 +278,4 @@ namespace LibMMD.Util
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,13 +75,15 @@ namespace LibMMD.Writer
|
||||
MMDReaderWriteUtil.WriteIndex(writer, joint.AssociatedRigidBodyIndex[0], pmxConfig.RigidBodyIndexSize);
|
||||
MMDReaderWriteUtil.WriteIndex(writer, joint.AssociatedRigidBodyIndex[1], pmxConfig.RigidBodyIndexSize);
|
||||
MMDReaderWriteUtil.WriteVector3(writer, joint.Position);
|
||||
MMDReaderWriteUtil.WriteAmpVector3(writer, joint.Rotation, Mathf.Rad2Deg);
|
||||
MMDReaderWriteUtil.WriteVector3(writer, joint.PositionLowLimit);
|
||||
MMDReaderWriteUtil.WriteVector3(writer, joint.PositionHiLimit);
|
||||
MMDReaderWriteUtil.WriteVector3(writer, joint.RotationLowLimit, false);
|
||||
MMDReaderWriteUtil.WriteVector3(writer, joint.RotationHiLimit, false);
|
||||
MMDReaderWriteUtil.WriteVector3(writer, joint.SpringTranslate);
|
||||
MMDReaderWriteUtil.WriteVector3(writer, joint.SpringRotate, false);
|
||||
MMDReaderWriteUtil.WriteEulerRotation(writer, joint.Rotation);
|
||||
MMDReaderWriteUtil.WritePositionLimitPair(
|
||||
writer, joint.PositionLowLimit, joint.PositionHiLimit);
|
||||
// PMX Joint 角限制和旋转弹簧是原始轴分量,单位为弧度,不属于空间坐标。
|
||||
MMDReaderWriteUtil.WriteRawVector3(writer, joint.RotationLowLimit);
|
||||
MMDReaderWriteUtil.WriteRawVector3(writer, joint.RotationHiLimit);
|
||||
// 平移弹簧是各轴刚度,不是带模型尺寸的空间位置。
|
||||
MMDReaderWriteUtil.WriteRawVector3(writer, joint.SpringTranslate);
|
||||
MMDReaderWriteUtil.WriteRawVector3(writer, joint.SpringRotate);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,12 +95,13 @@ namespace LibMMD.Writer
|
||||
MMDReaderWriteUtil.WriteSizedString(writer, rigidBody.Name, pmxConfig.Encoding); // Name
|
||||
MMDReaderWriteUtil.WriteSizedString(writer, rigidBody.NameEn, pmxConfig.Encoding); // NameEn
|
||||
MMDReaderWriteUtil.WriteIndex(writer, rigidBody.AssociatedBoneIndex, pmxConfig.BoneIndexSize); // AssociatedBoneIndex
|
||||
writer.Write(rigidBody.CollisionGroup); // CollisionGroup
|
||||
// PMX 的碰撞组字段固定为 1 字节;直接写 int 会令后续刚体数据错位。
|
||||
writer.Write((byte)rigidBody.CollisionGroup); // CollisionGroup
|
||||
writer.Write(rigidBody.CollisionMask); // CollisionMask
|
||||
writer.Write((byte)rigidBody.Shape); // Shape
|
||||
MMDReaderWriteUtil.WriteRawCoordinateVector3(writer, rigidBody.Dimemsions); // Dimemsions
|
||||
MMDReaderWriteUtil.WriteVector3(writer, rigidBody.Position); // Position
|
||||
MMDReaderWriteUtil.WriteAmpVector3(writer, rigidBody.Rotation, Mathf.Deg2Rad); // Rotation
|
||||
MMDReaderWriteUtil.WriteEulerRotation(writer, rigidBody.Rotation); // Rotation
|
||||
writer.Write(rigidBody.Mass); // Mass
|
||||
writer.Write(rigidBody.TranslateDamp); // TranslateDamp
|
||||
writer.Write(rigidBody.RotateDamp); // RotateDamp
|
||||
@@ -328,12 +331,33 @@ namespace LibMMD.Writer
|
||||
writer.Write(link.HasLimit ? (byte)1 : (byte)0);
|
||||
if (link.HasLimit)
|
||||
{
|
||||
MMDReaderWriteUtil.WriteVector3(writer, link.LoLimit, false);
|
||||
MMDReaderWriteUtil.WriteVector3(writer, link.HiLimit, false);
|
||||
WriteIkAngleLimits(writer, link.LoLimit, link.HiLimit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteIkAngleLimits(BinaryWriter writer, Vector3 lower, Vector3 upper)
|
||||
{
|
||||
ValidateFinite(lower, "IK lower limit");
|
||||
ValidateFinite(upper, "IK upper limit");
|
||||
|
||||
// PMX IK 区间是原始欧拉角弧度;不能复用空间向量的尺寸倍率或 X/Z 翻轴。
|
||||
Vector3 pmxLower = Vector3.Min(lower, upper);
|
||||
Vector3 pmxUpper = Vector3.Max(lower, upper);
|
||||
MMDReaderWriteUtil.WriteRawVector3(writer, pmxLower);
|
||||
MMDReaderWriteUtil.WriteRawVector3(writer, pmxUpper);
|
||||
}
|
||||
|
||||
private static void ValidateFinite(Vector3 value, string fieldName)
|
||||
{
|
||||
if (float.IsNaN(value.x) || float.IsInfinity(value.x) ||
|
||||
float.IsNaN(value.y) || float.IsInfinity(value.y) ||
|
||||
float.IsNaN(value.z) || float.IsInfinity(value.z))
|
||||
{
|
||||
throw new MMDFileParseException(fieldName + " contains NaN or Infinity");
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteParts(BinaryWriter writer, ModelConfig config, RawMMDModel model, PmxConfig pmxConfig)
|
||||
{
|
||||
var partNum = model.Parts.Length;
|
||||
@@ -552,4 +576,4 @@ namespace LibMMD.Writer
|
||||
writer.Write((byte)pmxConfig.RigidBodyIndexSize);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
左薬指1, 左薬指2, 左薬指3, 左小指1, 左小指2, 左小指3, 右親指1, 右親指2,
|
||||
右人指1, 右人指2, 右人指3, 右中指1, 右中指2, 右中指3, 右薬指1, 右薬指2,
|
||||
右薬指3, 右小指1, 右小指2, 右小指3, 左足, 右足, 左ひざ, 右ひざ,
|
||||
左足首, 右足首, 左足先EX, 右足先EX, None
|
||||
左足首, 右足首, 左足先EX, 右足先EX, 左目, 右目, 左耳, 右耳, 左耳1, 右耳1, 左耳2, 右耳2, 顎, 左親指0, 右親指0, None
|
||||
}
|
||||
//コンストラクタにて初期化
|
||||
//全てのボーンを名前で引く辞書
|
||||
@@ -54,8 +54,45 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
Dictionary<BoneNames, List<Vector3>> positionDictionary = new Dictionary<BoneNames, List<Vector3>>();
|
||||
Dictionary<BoneNames, List<Vector3>> positionDictionarySaved = new Dictionary<BoneNames, List<Vector3>>();
|
||||
Dictionary<BoneNames, List<Quaternion>> rotationDictionary = new Dictionary<BoneNames, List<Quaternion>>();
|
||||
Dictionary<BoneNames, List<Quaternion>> rotationDictionarySaved = new Dictionary<BoneNames, List<Quaternion>>();
|
||||
public Dictionary<BoneNames, List<Quaternion>> rotationDictionarySaved { get; private set; } = new Dictionary<BoneNames, List<Quaternion>>();
|
||||
Dictionary<int, bool> visitableDictionary = new Dictionary<int, bool>();
|
||||
|
||||
[Serializable]
|
||||
public struct MorphValue
|
||||
{
|
||||
public float value;
|
||||
public bool enabled;
|
||||
public MorphValue(float value, bool enabled)
|
||||
{
|
||||
this.value = value;
|
||||
this.enabled = enabled;
|
||||
}
|
||||
}
|
||||
|
||||
public struct BlendShapeLink
|
||||
{
|
||||
public SkinnedMeshRenderer renderer;
|
||||
public int index;
|
||||
public FacialMorph morph;
|
||||
public BlendShapeLink(SkinnedMeshRenderer renderer, int index, FacialMorph morph)
|
||||
{
|
||||
this.renderer = renderer;
|
||||
this.index = index;
|
||||
this.morph = morph;
|
||||
}
|
||||
}
|
||||
|
||||
public struct GhostEntry
|
||||
{
|
||||
public Transform ghost;
|
||||
public bool enabled;
|
||||
public GhostEntry(Transform ghost, bool enabled)
|
||||
{
|
||||
this.ghost = ghost;
|
||||
this.enabled = enabled;
|
||||
}
|
||||
}
|
||||
|
||||
//ボーン移動量の補正係数
|
||||
//この値は大体の値、正確ではない
|
||||
const float DefaultBoneAmplifier = 12.5f;
|
||||
@@ -81,59 +118,72 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
{
|
||||
//下半身などというものはUnityにはない
|
||||
{ BoneNames.全ての親, transform},
|
||||
{ BoneNames.センター, objs.Find(a=>a.name.Equals("Hip"))},
|
||||
{ BoneNames.上半身, objs.Find(a=>a.name.Equals("Spine"))},
|
||||
{ BoneNames.上半身2, objs.Find(a=>a.name.Equals("Chest"))},
|
||||
{ BoneNames.頭, objs.Find(a=>a.name.Equals("Head"))},
|
||||
{ BoneNames.首, objs.Find(a=>a.name.Equals("Neck"))},
|
||||
{ BoneNames.左肩, objs.Find(a=>a.name.Equals("Shoulder_L"))},
|
||||
{ BoneNames.右肩, objs.Find(a=>a.name.Equals("Shoulder_R"))},
|
||||
{ BoneNames.左腕, objs.Find(a=>a.name.Equals("Arm_L"))},
|
||||
{ BoneNames.右腕, objs.Find(a=>a.name.Equals("Arm_R"))},
|
||||
{ BoneNames.左ひじ, objs.Find(a=>a.name.Equals("Elbow_L"))},
|
||||
{ BoneNames.右ひじ, objs.Find(a=>a.name.Equals("Elbow_R"))},
|
||||
{ BoneNames.左手首, objs.Find(a=>a.name.Equals("Wrist_L"))},
|
||||
{ BoneNames.右手首, objs.Find(a=>a.name.Equals("Wrist_R"))},
|
||||
{ BoneNames.左親指1, objs.Find(a=>a.name.Equals("Thumb_02_L"))},
|
||||
{ BoneNames.右親指1, objs.Find(a=>a.name.Equals("Thumb_02_R"))},
|
||||
{ BoneNames.左親指2, objs.Find(a=>a.name.Equals("Thumb_03_L"))},
|
||||
{ BoneNames.右親指2, objs.Find(a=>a.name.Equals("Thumb_03_R"))},
|
||||
{ BoneNames.左人指1, objs.Find(a=>a.name.Equals("Index_01_L"))},
|
||||
{ BoneNames.右人指1, objs.Find(a=>a.name.Equals("Index_01_R"))},
|
||||
{ BoneNames.左人指2, objs.Find(a=>a.name.Equals("Index_02_L"))},
|
||||
{ BoneNames.右人指2, objs.Find(a=>a.name.Equals("Index_02_R"))},
|
||||
{ BoneNames.左人指3, objs.Find(a=>a.name.Equals("Index_03_L"))},
|
||||
{ BoneNames.右人指3, objs.Find(a=>a.name.Equals("Index_03_R"))},
|
||||
{ BoneNames.左中指1, objs.Find(a=>a.name.Equals("Middle_01_L"))},
|
||||
{ BoneNames.右中指1, objs.Find(a=>a.name.Equals("Middle_01_R"))},
|
||||
{ BoneNames.左中指2, objs.Find(a=>a.name.Equals("Middle_02_L"))},
|
||||
{ BoneNames.右中指2, objs.Find(a=>a.name.Equals("Middle_02_R"))},
|
||||
{ BoneNames.左中指3, objs.Find(a=>a.name.Equals("Middle_03_L"))},
|
||||
{ BoneNames.右中指3, objs.Find(a=>a.name.Equals("Middle_03_R"))},
|
||||
{ BoneNames.左薬指1, objs.Find(a=>a.name.Equals("Ring_01_L"))},
|
||||
{ BoneNames.右薬指1, objs.Find(a=>a.name.Equals("Ring_01_R"))},
|
||||
{ BoneNames.左薬指2, objs.Find(a=>a.name.Equals("Ring_02_L"))},
|
||||
{ BoneNames.右薬指2, objs.Find(a=>a.name.Equals("Ring_02_R"))},
|
||||
{ BoneNames.左薬指3, objs.Find(a=>a.name.Equals("Ring_03_L"))},
|
||||
{ BoneNames.右薬指3, objs.Find(a=>a.name.Equals("Ring_03_R"))},
|
||||
{ BoneNames.左小指1, objs.Find(a=>a.name.Equals("Pinky_01_L"))},
|
||||
{ BoneNames.右小指1, objs.Find(a=>a.name.Equals("Pinky_01_R"))},
|
||||
{ BoneNames.左小指2, objs.Find(a=>a.name.Equals("Pinky_02_L"))},
|
||||
{ BoneNames.右小指2, objs.Find(a=>a.name.Equals("Pinky_02_R"))},
|
||||
{ BoneNames.左小指3, objs.Find(a=>a.name.Equals("Pinky_03_L"))},
|
||||
{ BoneNames.右小指3, objs.Find(a=>a.name.Equals("Pinky_03_R"))},
|
||||
{ BoneNames.左足IK, objs.Find(a=>a.name.Equals("Ankle_L"))},
|
||||
{ BoneNames.右足IK, objs.Find(a=>a.name.Equals("Ankle_R"))},
|
||||
{ BoneNames.左足, objs.Find(a=>a.name.Equals("Thigh_L"))},
|
||||
{ BoneNames.右足, objs.Find(a=>a.name.Equals("Thigh_R"))},
|
||||
{ BoneNames.左ひざ, objs.Find(a=>a.name.Equals("Knee_L"))},
|
||||
{ BoneNames.右ひざ, objs.Find(a=>a.name.Equals("Knee_R"))},
|
||||
{ BoneNames.左足首, objs.Find(a=>a.name.Equals("Ankle_L"))},
|
||||
{ BoneNames.右足首, objs.Find(a=>a.name.Equals("Ankle_R"))},
|
||||
{ BoneNames.左足先EX, objs.Find(a=>a.name.Equals("Toe_L"))},
|
||||
{ BoneNames.右足先EX, objs.Find(a=>a.name.Equals("Toe_R"))}
|
||||
{ BoneNames.センター, objs.Find(a=>a.name.Equals("Hip", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.上半身, objs.Find(a=>a.name.Equals("Spine", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.上半身2, objs.Find(a=>a.name.Equals("Chest", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.頭, objs.Find(a=>a.name.Equals("Head", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.首, objs.Find(a=>a.name.Equals("Neck", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左肩, objs.Find(a=>a.name.Equals("Shoulder_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右肩, objs.Find(a=>a.name.Equals("Shoulder_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左腕, objs.Find(a=>a.name.Equals("Arm_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右腕, objs.Find(a=>a.name.Equals("Arm_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左ひじ, objs.Find(a=>a.name.Equals("Elbow_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右ひじ, objs.Find(a=>a.name.Equals("Elbow_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左手首, objs.Find(a=>a.name.Equals("Wrist_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右手首, objs.Find(a=>a.name.Equals("Wrist_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左親指1, objs.Find(a=>a.name.Equals("Thumb_02_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右親指1, objs.Find(a=>a.name.Equals("Thumb_02_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左親指2, objs.Find(a=>a.name.Equals("Thumb_03_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右親指2, objs.Find(a=>a.name.Equals("Thumb_03_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左人指1, objs.Find(a=>a.name.Equals("Index_01_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右人指1, objs.Find(a=>a.name.Equals("Index_01_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左人指2, objs.Find(a=>a.name.Equals("Index_02_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右人指2, objs.Find(a=>a.name.Equals("Index_02_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左人指3, objs.Find(a=>a.name.Equals("Index_03_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右人指3, objs.Find(a=>a.name.Equals("Index_03_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左中指1, objs.Find(a=>a.name.Equals("Middle_01_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右中指1, objs.Find(a=>a.name.Equals("Middle_01_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左中指2, objs.Find(a=>a.name.Equals("Middle_02_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右中指2, objs.Find(a=>a.name.Equals("Middle_02_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左中指3, objs.Find(a=>a.name.Equals("Middle_03_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右中指3, objs.Find(a=>a.name.Equals("Middle_03_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左薬指1, objs.Find(a=>a.name.Equals("Ring_01_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右薬指1, objs.Find(a=>a.name.Equals("Ring_01_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左薬指2, objs.Find(a=>a.name.Equals("Ring_02_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右薬指2, objs.Find(a=>a.name.Equals("Ring_02_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左薬指3, objs.Find(a=>a.name.Equals("Ring_03_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右薬指3, objs.Find(a=>a.name.Equals("Ring_03_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左小指1, objs.Find(a=>a.name.Equals("Pinky_01_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右小指1, objs.Find(a=>a.name.Equals("Pinky_01_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左小指2, objs.Find(a=>a.name.Equals("Pinky_02_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右小指2, objs.Find(a=>a.name.Equals("Pinky_02_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左小指3, objs.Find(a=>a.name.Equals("Pinky_03_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右小指3, objs.Find(a=>a.name.Equals("Pinky_03_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左足IK, objs.Find(a=>a.name.Equals("Ankle_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右足IK, objs.Find(a=>a.name.Equals("Ankle_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左足, objs.Find(a=>a.name.Equals("Thigh_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右足, objs.Find(a=>a.name.Equals("Thigh_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左ひざ, objs.Find(a=>a.name.Equals("Knee_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右ひざ, objs.Find(a=>a.name.Equals("Knee_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左足首, objs.Find(a=>a.name.Equals("Ankle_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右足首, objs.Find(a=>a.name.Equals("Ankle_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左足先EX, objs.Find(a=>a.name.Equals("Toe_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右足先EX, objs.Find(a=>a.name.Equals("Toe_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左目, objs.Find(a=>a.name.Equals("Eye_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右目, objs.Find(a=>a.name.Equals("Eye_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左耳, objs.Find(a=>a.name.Equals("Ear_01_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左耳1, objs.Find(a=>a.name.Equals("Ear_02_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左耳2, objs.Find(a=>a.name.Equals("Ear_03_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右耳, objs.Find(a=>a.name.Equals("Ear_01_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右耳1, objs.Find(a=>a.name.Equals("Ear_02_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右耳2, objs.Find(a=>a.name.Equals("Ear_03_R", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.顎, objs.Find(a=>a.name.Equals("Jaw", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.左親指0, objs.Find(a=>a.name.Equals("Thumb_01_L", StringComparison.OrdinalIgnoreCase))},
|
||||
{ BoneNames.右親指0, objs.Find(a=>a.name.Equals("Thumb_01_R", StringComparison.OrdinalIgnoreCase))}
|
||||
};
|
||||
|
||||
Debug.Log($"VMDRecorder initialized. Bones matched: {BoneDictionary.Count(b => b.Value != null)}/{BoneDictionary.Count}");
|
||||
|
||||
foreach (KeyValuePair<BoneNames, Transform> pair in BoneDictionary)
|
||||
{
|
||||
transformDictionary.Add(pair.Key.ToString(), pair.Value);
|
||||
@@ -144,12 +194,11 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
var state = animator.GetCurrentAnimatorStateInfo(0);
|
||||
animator.enabled = false;
|
||||
|
||||
// Set to T-Pose
|
||||
// 先回到初始化姿势,再切换为 PMX 导出共用的 MMD 默认 A-pose。
|
||||
characterContainer.ResetBodyPose();
|
||||
characterContainer.UpBodyReset();
|
||||
|
||||
BoneDictionary[BoneNames.左腕].Rotate(0, 0, -aposeDegress);
|
||||
BoneDictionary[BoneNames.右腕].Rotate(0, 0, aposeDegress);
|
||||
BoneDictionary[BoneNames.左腕]?.Rotate(0, 0, -aposeDegress);
|
||||
BoneDictionary[BoneNames.右腕]?.Rotate(0, 0, aposeDegress);
|
||||
|
||||
SetInitialPositionAndRotation();
|
||||
|
||||
@@ -174,8 +223,9 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
boneGhost = new BoneGhost(BoneDictionary, UseBottomCenter);
|
||||
morphRecorder = new MorphRecorder(transform);
|
||||
|
||||
BoneDictionary[BoneNames.左腕].Rotate(0, 0, aposeDegress);
|
||||
BoneDictionary[BoneNames.右腕].Rotate(0, 0, -aposeDegress);
|
||||
// Ghost 建立后撤销临时参考旋转,让 Animator 从原动画状态继续驱动角色。
|
||||
BoneDictionary[BoneNames.左腕]?.Rotate(0, 0, aposeDegress);
|
||||
BoneDictionary[BoneNames.右腕]?.Rotate(0, 0, -aposeDegress);
|
||||
animator.enabled = true;
|
||||
animator.Play(state.shortNameHash, 0, state.normalizedTime);
|
||||
}
|
||||
@@ -193,7 +243,24 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
void SaveFrame()
|
||||
{
|
||||
if (boneGhost != null) { boneGhost.GhostAll(); }
|
||||
if (morphRecorder != null) { morphRecorder.RecrodAllMorph(); }
|
||||
|
||||
// 确保表情/耳朵morph weight从Locator动画数据更新
|
||||
// ProcessLocator 通常只在isAnimatorControl=true时由UmaContainerCharacter.FixedUpdate调用
|
||||
// 录制时需要强制更新,否则morph weight全为0
|
||||
// FaceDrivenKeyTarget在isAnimatorControl为true时(如播放动画片段)会由Animator驱动,不需要手动ProcessLocator
|
||||
// 如果在isAnimatorControl为true时手动调用ProcessLocator,可能会因为Locator位置未更新而重置表情
|
||||
if (container is UmaContainerCharacter characterContainer && characterContainer.FaceDrivenKeyTarget != null && characterContainer.FaceDrivenKeyTarget.DrivenKeyLocator != null)
|
||||
{
|
||||
// [Fix] Force update locator to ensure morph weights are updated during recording
|
||||
// Even if animator is control, we call this to guarantee we have weights.
|
||||
characterContainer.FaceDrivenKeyTarget.ProcessLocator();
|
||||
}
|
||||
|
||||
if (morphRecorder != null)
|
||||
{
|
||||
morphRecorder.UpdateWeights(); // [NEW] Sync SMR weights
|
||||
morphRecorder.RecrodAllMorph();
|
||||
}
|
||||
|
||||
bool visable = container.LiveVisible;
|
||||
if (visitableDictionary.Count == 0)
|
||||
@@ -255,6 +322,8 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
|
||||
if (boneGhost != null && boneGhost.GhostDictionary.Keys.Contains(boneName))
|
||||
{
|
||||
if (boneGhost.GhostDictionary[boneName].ghost == null || !boneGhost.GhostDictionary[boneName].enabled)
|
||||
@@ -264,16 +333,29 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
continue;
|
||||
}
|
||||
|
||||
Vector3 boneVector = boneGhost.GhostDictionary[boneName].ghost.localPosition;
|
||||
// Calculate rotation normally
|
||||
Quaternion boneQuatenion = boneGhost.GhostDictionary[boneName].ghost.localRotation;
|
||||
rotationDictionary[boneName].Add(new Quaternion(-boneQuatenion.x, boneQuatenion.y, -boneQuatenion.z, boneQuatenion.w));
|
||||
Quaternion deltaRotation = Quaternion.Inverse(boneGhost.GhostOriginalLocalRotationDictionary[boneName]) * boneQuatenion;
|
||||
|
||||
// Add rotation (converted to MMD coordinate system)
|
||||
rotationDictionary[boneName].Add(new Quaternion(-deltaRotation.x, deltaRotation.y, -deltaRotation.z, deltaRotation.w));
|
||||
|
||||
boneVector -= boneGhost.GhostOriginalLocalPositionDictionary[boneName];
|
||||
|
||||
positionDictionary[boneName].Add(new Vector3(-boneVector.x, boneVector.y, -boneVector.z) * DefaultBoneAmplifier);
|
||||
// For Eyes, force position to zero to prevent "flying out"
|
||||
if (boneName == BoneNames.左目 || boneName == BoneNames.右目)
|
||||
{
|
||||
positionDictionary[boneName].Add(Vector3.zero);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Calculate and add position normally for other bones
|
||||
Vector3 boneVector = boneGhost.GhostDictionary[boneName].ghost.localPosition;
|
||||
boneVector -= boneGhost.GhostOriginalLocalPositionDictionary[boneName];
|
||||
positionDictionary[boneName].Add(new Vector3(-boneVector.x, boneVector.y, -boneVector.z));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
Quaternion fixedQuatenion = Quaternion.identity;
|
||||
Quaternion vmdRotation = Quaternion.identity;
|
||||
|
||||
@@ -327,11 +409,8 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
|
||||
void LiveSaveFrame()
|
||||
{
|
||||
if (IsRecording && IsLive)
|
||||
{
|
||||
SaveFrame();
|
||||
FrameNumber++;
|
||||
}
|
||||
SaveFrame();
|
||||
FrameNumber++;
|
||||
}
|
||||
|
||||
void SetInitialPositionAndRotation()
|
||||
@@ -358,6 +437,24 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
/// </summary>
|
||||
public void StartRecording(bool islive = false)
|
||||
{
|
||||
// [Fix] Disable Culling to ensure bone/blendshape updates when off-screen
|
||||
var smrs = GetComponentsInChildren<SkinnedMeshRenderer>();
|
||||
foreach (var smr in smrs)
|
||||
{
|
||||
smr.updateWhenOffscreen = true;
|
||||
}
|
||||
var animator = GetComponentInParent<Animator>();
|
||||
if (animator) animator.cullingMode = AnimatorCullingMode.AlwaysAnimate;
|
||||
|
||||
// [Fix] Ensure Face Animator is also always animating (for expressions when offscreen)
|
||||
if (container is UmaContainerCharacter character && character.FaceDrivenKeyTarget != null)
|
||||
{
|
||||
if (character.UmaFaceAnimator != null)
|
||||
{
|
||||
character.UmaFaceAnimator.cullingMode = AnimatorCullingMode.AlwaysAnimate;
|
||||
}
|
||||
}
|
||||
|
||||
SetInitialPositionAndRotation();
|
||||
IsRecording = true;
|
||||
IsLive = islive;
|
||||
@@ -426,7 +523,11 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
{
|
||||
try
|
||||
{
|
||||
const string ShiftJIS = "shift_jis";
|
||||
string ShiftJIS = "shift_jis";
|
||||
// [Fix] Fallback for environments without shift_jis support
|
||||
try { System.Text.Encoding.GetEncoding(ShiftJIS); }
|
||||
catch { ShiftJIS = "utf-8"; Debug.LogWarning("Shift_JIS not supported, fallback to UTF-8. Animation names might be broken in MMD."); }
|
||||
|
||||
const int intByteLength = 4;
|
||||
|
||||
//ファイルタイプの書き込み
|
||||
@@ -465,9 +566,11 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
byte[] allKeyFrameNumberByte = BitConverter.GetBytes(allKeyFrameNumber);
|
||||
binaryWriter.Write(allKeyFrameNumberByte, 0, intByteLength);
|
||||
|
||||
uint boneWritten = 0;
|
||||
//人ボーンの書き込み
|
||||
LoopWithBoneCondition((boneName, i) =>
|
||||
{
|
||||
boneWritten++;
|
||||
const int boneNameLength = 15;
|
||||
string boneNameString = boneName.ToString();
|
||||
if (boneName == BoneNames.全ての親 && UseCenterAsParentOfAll)
|
||||
@@ -480,10 +583,19 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
}
|
||||
|
||||
byte[] boneNameBytes = System.Text.Encoding.GetEncoding(ShiftJIS).GetBytes(boneNameString);
|
||||
if (boneNameBytes.Length > boneNameLength)
|
||||
{
|
||||
string truncated = boneNameString;
|
||||
while(System.Text.Encoding.GetEncoding(ShiftJIS).GetByteCount(truncated) > boneNameLength)
|
||||
{
|
||||
truncated = truncated.Substring(0, truncated.Length - 1);
|
||||
}
|
||||
boneNameBytes = System.Text.Encoding.GetEncoding(ShiftJIS).GetBytes(truncated);
|
||||
}
|
||||
binaryWriter.Write(boneNameBytes, 0, boneNameBytes.Length);
|
||||
binaryWriter.Write(new byte[boneNameLength - boneNameBytes.Length], 0, boneNameLength - boneNameBytes.Length);
|
||||
|
||||
byte[] frameNumberByte = BitConverter.GetBytes((ulong)i);
|
||||
byte[] frameNumberByte = BitConverter.GetBytes((uint)i);
|
||||
binaryWriter.Write(frameNumberByte, 0, intByteLength);
|
||||
|
||||
Vector3 position = positionDictionarySaved[boneName][i];
|
||||
@@ -493,6 +605,7 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
binaryWriter.Write(positionY, 0, intByteLength);
|
||||
byte[] positionZ = BitConverter.GetBytes(position.z);
|
||||
binaryWriter.Write(positionZ, 0, intByteLength);
|
||||
|
||||
Quaternion rotation = rotationDictionarySaved[boneName][i];
|
||||
byte[] rotationX = BitConverter.GetBytes(rotation.x);
|
||||
binaryWriter.Write(rotationX, 0, intByteLength);
|
||||
@@ -506,6 +619,7 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
byte[] interpolateBytes = new byte[64];
|
||||
binaryWriter.Write(interpolateBytes, 0, 64);
|
||||
});
|
||||
Debug.Log($"VMD Bones frames written: {boneWritten}");
|
||||
|
||||
//全モーフフレーム数の書き込み
|
||||
morphRecorderSaved.DisableIntron();
|
||||
@@ -517,15 +631,9 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
foreach (string morphName in morphRecorderSaved.MorphDrivers.Keys)
|
||||
{
|
||||
if (morphRecorderSaved.MorphDrivers[morphName].ValueList.Count == 0) { continue; }
|
||||
if (i > morphRecorderSaved.MorphDrivers[morphName].ValueList.Count) { continue; }
|
||||
if (i >= morphRecorderSaved.MorphDrivers[morphName].ValueList.Count) { continue; }
|
||||
//変化のない部分は省く
|
||||
if (!morphRecorderSaved.MorphDrivers[morphName].ValueList[i].enabled) { continue; }
|
||||
const int boneNameLength = 15;
|
||||
string morphNameString = morphName.ToString();
|
||||
byte[] morphNameBytes = System.Text.Encoding.GetEncoding(ShiftJIS).GetBytes(morphNameString);
|
||||
//名前が長過ぎた場合書き込まない
|
||||
if (boneNameLength - morphNameBytes.Length < 0) { continue; }
|
||||
|
||||
action(morphName, i);
|
||||
}
|
||||
}
|
||||
@@ -535,22 +643,35 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
byte[] faceFrameCount = BitConverter.GetBytes(allMorphNumber);
|
||||
binaryWriter.Write(faceFrameCount, 0, intByteLength);
|
||||
|
||||
uint morphWritten = 0;
|
||||
//モーフの書き込み
|
||||
LoopWithMorphCondition((morphName, i) =>
|
||||
{
|
||||
morphWritten++;
|
||||
const int boneNameLength = 15;
|
||||
string morphNameString = morphName.ToString();
|
||||
|
||||
byte[] morphNameBytes = System.Text.Encoding.GetEncoding(ShiftJIS).GetBytes(morphNameString);
|
||||
if (morphNameBytes.Length > boneNameLength)
|
||||
{
|
||||
string truncated = morphNameString;
|
||||
while(System.Text.Encoding.GetEncoding(ShiftJIS).GetByteCount(truncated) > boneNameLength)
|
||||
{
|
||||
truncated = truncated.Substring(0, truncated.Length - 1);
|
||||
}
|
||||
morphNameBytes = System.Text.Encoding.GetEncoding(ShiftJIS).GetBytes(truncated);
|
||||
}
|
||||
|
||||
binaryWriter.Write(morphNameBytes, 0, morphNameBytes.Length);
|
||||
binaryWriter.Write(new byte[boneNameLength - morphNameBytes.Length], 0, boneNameLength - morphNameBytes.Length);
|
||||
|
||||
byte[] frameNumberByte = BitConverter.GetBytes((ulong)i);
|
||||
byte[] frameNumberByte = BitConverter.GetBytes((uint)i);
|
||||
binaryWriter.Write(frameNumberByte, 0, intByteLength);
|
||||
|
||||
byte[] valueByte = BitConverter.GetBytes(morphRecorderSaved.MorphDrivers[morphName].ValueList[i].value);
|
||||
binaryWriter.Write(valueByte, 0, intByteLength);
|
||||
});
|
||||
Debug.Log($"VMD Morph frames written: {morphWritten}");
|
||||
|
||||
//カメラの書き込み
|
||||
byte[] cameraFrameCount = BitConverter.GetBytes(0);
|
||||
@@ -614,7 +735,10 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
{
|
||||
foreach(var pair in boneGhost.GhostDictionary)
|
||||
{
|
||||
Destroy(pair.Value.ghost.gameObject);
|
||||
if (pair.Value.ghost != null)
|
||||
{
|
||||
Destroy(pair.Value.ghost.gameObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
Destroy(this);
|
||||
@@ -647,9 +771,11 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
//(初期ポーズで各ボーンのlocalRotationがQuaternion.identityのモデル)を疑似的にアニメーションさせる
|
||||
class BoneGhost
|
||||
{
|
||||
public Dictionary<BoneNames, (Transform ghost, bool enabled)> GhostDictionary { get; private set; } = new Dictionary<BoneNames, (Transform ghost, bool enabled)>();
|
||||
public Dictionary<BoneNames, GhostEntry> GhostDictionary { get; private set; } = new Dictionary<BoneNames, GhostEntry>();
|
||||
public Dictionary<BoneNames, Vector3> GhostOriginalLocalPositionDictionary { get; private set; } = new Dictionary<BoneNames, Vector3>();
|
||||
public Dictionary<BoneNames, Quaternion> GhostOriginalRotationDictionary { get; private set; } = new Dictionary<BoneNames, Quaternion>();
|
||||
// Ghost骨骼的初始局部旋转(用于计算旋转增量,与位置差值对应)
|
||||
public Dictionary<BoneNames, Quaternion> GhostOriginalLocalRotationDictionary { get; private set; } = new Dictionary<BoneNames, Quaternion>();
|
||||
public Dictionary<BoneNames, Quaternion> OriginalRotationDictionary { get; private set; } = new Dictionary<BoneNames, Quaternion>();
|
||||
|
||||
public bool UseBottomCenter { get; private set; } = false;
|
||||
@@ -708,6 +834,17 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
{ BoneNames.右人指3, (BoneNames.右人指2, BoneNames.None, BoneNames.None) },
|
||||
{ BoneNames.右中指1, (BoneNames.右手首, BoneNames.None, BoneNames.None) },
|
||||
{ BoneNames.右中指2, (BoneNames.右中指1, BoneNames.None, BoneNames.None) },
|
||||
{ BoneNames.左目, (BoneNames.頭, BoneNames.None, BoneNames.None) },
|
||||
{ BoneNames.右目, (BoneNames.頭, BoneNames.None, BoneNames.None) },
|
||||
{ BoneNames.左耳, (BoneNames.頭, BoneNames.None, BoneNames.None) },
|
||||
{ BoneNames.左耳1, (BoneNames.左耳, BoneNames.None, BoneNames.None) },
|
||||
{ BoneNames.左耳2, (BoneNames.左耳1, BoneNames.None, BoneNames.None) },
|
||||
{ BoneNames.右耳, (BoneNames.頭, BoneNames.None, BoneNames.None) },
|
||||
{ BoneNames.右耳1, (BoneNames.右耳, BoneNames.None, BoneNames.None) },
|
||||
{ BoneNames.右耳2, (BoneNames.右耳1, BoneNames.None, BoneNames.None) },
|
||||
{ BoneNames.顎, (BoneNames.頭, BoneNames.None, BoneNames.None) },
|
||||
{ BoneNames.左親指0, (BoneNames.左手首, BoneNames.None, BoneNames.None) },
|
||||
{ BoneNames.右親指0, (BoneNames.右手首, BoneNames.None, BoneNames.None) },
|
||||
{ BoneNames.右中指3, (BoneNames.右中指2, BoneNames.None, BoneNames.None) },
|
||||
{ BoneNames.右薬指1, (BoneNames.右手首, BoneNames.None, BoneNames.None) },
|
||||
{ BoneNames.右薬指2, (BoneNames.右薬指1, BoneNames.None, BoneNames.None) },
|
||||
@@ -727,7 +864,7 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
|
||||
if (boneDictionary[boneName] == null)
|
||||
{
|
||||
GhostDictionary.Add(boneName, (null, false));
|
||||
GhostDictionary.Add(boneName, new GhostEntry(null, false));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -740,7 +877,7 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
{
|
||||
ghost.position = boneDictionary[boneName].position;
|
||||
}
|
||||
GhostDictionary.Add(boneName, (ghost, true));
|
||||
GhostDictionary.Add(boneName, new GhostEntry(ghost, true));
|
||||
}
|
||||
|
||||
//Ghostの親子構造を設定
|
||||
@@ -776,7 +913,7 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
}
|
||||
else
|
||||
{
|
||||
GhostDictionary[boneName] = (GhostDictionary[boneName].ghost, false);
|
||||
GhostDictionary[boneName] = new GhostEntry(GhostDictionary[boneName].ghost, false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -787,11 +924,13 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
{
|
||||
GhostOriginalLocalPositionDictionary.Add(boneName, Vector3.zero);
|
||||
GhostOriginalRotationDictionary.Add(boneName, Quaternion.identity);
|
||||
GhostOriginalLocalRotationDictionary.Add(boneName, Quaternion.identity);
|
||||
OriginalRotationDictionary.Add(boneName, Quaternion.identity);
|
||||
}
|
||||
else
|
||||
{
|
||||
GhostOriginalRotationDictionary.Add(boneName, GhostDictionary[boneName].ghost.rotation);
|
||||
GhostOriginalLocalRotationDictionary.Add(boneName, GhostDictionary[boneName].ghost.localRotation);
|
||||
OriginalRotationDictionary.Add(boneName, boneDictionary[boneName].rotation);
|
||||
if (boneName == BoneNames.センター && UseBottomCenter)
|
||||
{
|
||||
@@ -833,9 +972,59 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
{
|
||||
var facialTarget = model.GetComponentInParent<UmaContainerCharacter>().FaceDrivenKeyTarget;
|
||||
FacialMorphList = new List<FacialMorph>();
|
||||
FacialMorphList.AddRange(facialTarget.EarMorphs); // 耳朵morph(之前缺失)
|
||||
FacialMorphList.AddRange(facialTarget.EyeBrowMorphs);
|
||||
FacialMorphList.AddRange(facialTarget.EyeMorphs);
|
||||
FacialMorphList.AddRange(facialTarget.MouthMorphs);
|
||||
// [NEW] Scan all SkinnedMeshRenderers to capture Standard Animation blendshapes
|
||||
// User Request: Remove this "baking" scanning.
|
||||
// It captures too many raw blendshapes and makes the effect hard to control in VMD.
|
||||
// We will only stick to the explicit FaceDrivenKeyTarget morphs added above.
|
||||
/*
|
||||
var smrs = model.GetComponentsInChildren<SkinnedMeshRenderer>();
|
||||
foreach (var smr in smrs)
|
||||
{
|
||||
if (!smr.sharedMesh) continue;
|
||||
for (int i = 0; i < smr.sharedMesh.blendShapeCount; i++)
|
||||
{
|
||||
string shapeName = smr.sharedMesh.GetBlendShapeName(i);
|
||||
FacialMorph targetMorph = null;
|
||||
|
||||
// Check if this morph is already managed by FaceDrivenKeyTarget
|
||||
// We need to find if there is an existing FacialMorph with this name
|
||||
foreach (var m in FacialMorphList)
|
||||
{
|
||||
// [Fix] Compare RAW names case-insensitively first!
|
||||
// ConvertMorphName might fail for 'mouth_a' if config only has 'Mouth_A', diverging the names.
|
||||
if (string.Equals(m.name, shapeName, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
targetMorph = m;
|
||||
break;
|
||||
}
|
||||
|
||||
// Fallback: check converted names (in case of aliases)
|
||||
string n1 = ConvertMorphName(m.name);
|
||||
string n2 = ConvertMorphName(shapeName);
|
||||
if (string.Equals(n1, n2, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
targetMorph = m;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If not found, create a new one
|
||||
if (targetMorph == null)
|
||||
{
|
||||
targetMorph = new FacialMorph { name = shapeName };
|
||||
FacialMorphList.Add(targetMorph);
|
||||
}
|
||||
|
||||
// Register for update
|
||||
BlendShapeLinks.Add((smr, i, targetMorph));
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
for (int i = 0; i < FacialMorphList.Count; i++)
|
||||
{
|
||||
string morphName = ConvertMorphName(FacialMorphList[i].name);
|
||||
@@ -857,6 +1046,20 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
}
|
||||
}
|
||||
|
||||
private List<BlendShapeLink> BlendShapeLinks = new List<BlendShapeLink>();
|
||||
|
||||
public void UpdateWeights()
|
||||
{
|
||||
foreach (BlendShapeLink link in BlendShapeLinks)
|
||||
{
|
||||
if (link.renderer != null)
|
||||
{
|
||||
float weight = link.renderer.GetBlendShapeWeight(link.index);
|
||||
link.morph.weight = weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public string ConvertMorphName(string name)
|
||||
{
|
||||
@@ -916,7 +1119,7 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
&& floatCompare(MorphDrivers[morphName].ValueList[i].value, MorphDrivers[morphName].ValueList[i - 1].value)
|
||||
&& floatCompare(MorphDrivers[morphName].ValueList[i].value, MorphDrivers[morphName].ValueList[i + 1].value))
|
||||
{
|
||||
MorphDrivers[morphName].ValueList[i] = (MorphDrivers[morphName].ValueList[i].value, false);
|
||||
MorphDrivers[morphName].ValueList[i] = new MorphValue(MorphDrivers[morphName].ValueList[i].value, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -936,7 +1139,7 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
|
||||
public int MorphIndex { get; private set; }
|
||||
|
||||
public List<(float value, bool enabled)> ValueList = new List<(float value, bool enabled)>();
|
||||
public List<MorphValue> ValueList = new List<MorphValue>();
|
||||
|
||||
public MorphDriver(List<FacialMorph> facialMorph, int morphIndex)
|
||||
{
|
||||
@@ -951,8 +1154,9 @@ public class UnityHumanoidVMDRecorder : MonoBehaviour
|
||||
{
|
||||
val += morph.weight;
|
||||
}
|
||||
ValueList.Add((Mathf.Clamp(val, -1, 1), true));
|
||||
// [Fix] Remove Clamp to support values > 1 (0-100 range)
|
||||
ValueList.Add(new MorphValue(val, true));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user