import pmx plugin

This commit is contained in:
CroakFang
2023-06-30 14:08:40 +08:00
parent c3d4e6b111
commit 33943e4205
203 changed files with 11810 additions and 0 deletions
@@ -0,0 +1,277 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using LibMMD.Unity3D;
using System.Diagnostics;
using System.Threading.Tasks;
namespace LibMMD.Unity3D
{
public class AvatarMaker : MonoBehaviour
{
public RuntimeAnimatorController RuntimeAnimatorController;
const string AvatarNameTail = "Avatar";
private MMDModel model;
private SkinnedMeshRenderer skinnedMeshRenderer;
//BuildAvatarするまでnull
private Animator animator;
Dictionary<string, Transform> humanBoneDictionary = new Dictionary<string, Transform>();
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void Prepare(MMDModel mmdModel, RuntimeAnimatorController runtimeAnimatorController)
{
model = mmdModel;
RuntimeAnimatorController = runtimeAnimatorController;
humanBoneDictionary = MakeHumanBoneDictionary(transform);
skinnedMeshRenderer = mmdModel.SkinnedMeshRenderer;
}
public void Prepare(MMDModel mmdModel)
{
Prepare(mmdModel, null);
}
public async Task<bool> MakeAvatar()
{
bool fixedBone = await FixBoneWeight();
if (!fixedBone)
{
UnityEngine.Debug.Log("Failed to fix bone.");
return false;
}
EnforceTPose();
return await BuildAvatar();
}
private void EnforceTPose()
{
Vector3 right = transform.right;
Vector3 left = -right;
Vector3 rightUpperArmToLowerArm = humanBoneDictionary[MMDModel.Unity_MMDBoneNameDictionary[MMDModel.RightLowerArm]].position - humanBoneDictionary[MMDModel.Unity_MMDBoneNameDictionary[MMDModel.RightUpperArm]].position;
Vector3 leftUpperArmToLowerArm = humanBoneDictionary[MMDModel.Unity_MMDBoneNameDictionary[MMDModel.LeftLowerArm]].position - humanBoneDictionary[MMDModel.Unity_MMDBoneNameDictionary[MMDModel.LeftUpperArm]].position;
humanBoneDictionary[MMDModel.Unity_MMDBoneNameDictionary[MMDModel.RightUpperArm]].Rotate(Vector3.Cross(rightUpperArmToLowerArm, right), Vector3.Angle(rightUpperArmToLowerArm, right));
humanBoneDictionary[MMDModel.Unity_MMDBoneNameDictionary[MMDModel.LeftUpperArm]].Rotate(Vector3.Cross(leftUpperArmToLowerArm, left), Vector3.Angle(leftUpperArmToLowerArm, left));
Vector3 leftHandToMiddleFinger = humanBoneDictionary[MMDModel.Unity_MMDBoneNameDictionary[MMDModel.LeftMiddleProximal]].position - humanBoneDictionary[MMDModel.Unity_MMDBoneNameDictionary[MMDModel.LeftHand]].position;
Vector3 rightHandToMiddleFinger = humanBoneDictionary[MMDModel.Unity_MMDBoneNameDictionary[MMDModel.RightMiddleProximal]].position - humanBoneDictionary[MMDModel.Unity_MMDBoneNameDictionary[MMDModel.RightHand]].position;
Vector3 projectedLeftHandToMiddleFinger = Vector3.ProjectOnPlane(leftHandToMiddleFinger, transform.up);
Vector3 projectedRightHandToMiddleFinger = Vector3.ProjectOnPlane(rightHandToMiddleFinger, transform.up);
humanBoneDictionary[MMDModel.Unity_MMDBoneNameDictionary[MMDModel.LeftHand]].Rotate(Vector3.Cross(leftHandToMiddleFinger, projectedLeftHandToMiddleFinger), Vector3.Angle(leftHandToMiddleFinger, projectedLeftHandToMiddleFinger));
humanBoneDictionary[MMDModel.Unity_MMDBoneNameDictionary[MMDModel.RightHand]].Rotate(Vector3.Cross(rightHandToMiddleFinger, projectedRightHandToMiddleFinger), Vector3.Angle(rightHandToMiddleFinger, projectedRightHandToMiddleFinger));
rightHandToMiddleFinger = humanBoneDictionary[MMDModel.Unity_MMDBoneNameDictionary[MMDModel.RightMiddleProximal]].position - humanBoneDictionary[MMDModel.Unity_MMDBoneNameDictionary[MMDModel.RightHand]].position;
leftHandToMiddleFinger = humanBoneDictionary[MMDModel.Unity_MMDBoneNameDictionary[MMDModel.LeftMiddleProximal]].position - humanBoneDictionary[MMDModel.Unity_MMDBoneNameDictionary[MMDModel.LeftHand]].position;
humanBoneDictionary[MMDModel.Unity_MMDBoneNameDictionary[MMDModel.RightHand]].Rotate(-Vector3.Cross(rightHandToMiddleFinger, right), Vector3.Angle(rightHandToMiddleFinger, right));
humanBoneDictionary[MMDModel.Unity_MMDBoneNameDictionary[MMDModel.LeftHand]].Rotate(-Vector3.Cross(leftHandToMiddleFinger, left), Vector3.Angle(leftHandToMiddleFinger, left));
}
private async Task<bool> BuildAvatar()
{
// HumanBoneのためのリストを取得する
List<HumanBone> humanBones = new List<HumanBone>();
string[] boneNames = HumanTrait.BoneName;
await Task.Run(() =>
{
foreach (string humanBoneName in boneNames)
{
if (!MMDModel.Unity_MMDBoneNameDictionary.ContainsKey(humanBoneName)) { continue; }
if (MMDModel.Unity_MMDBoneNameDictionary[humanBoneName] == null) { continue; }
HumanBone humanBone = new HumanBone();
humanBone.humanName = humanBoneName;
humanBone.boneName = MMDModel.Unity_MMDBoneNameDictionary[humanBoneName];
humanBone.limit.useDefaultValues = true;
humanBones.Add(humanBone);
}
});
// HumanDescription(関節の曲がり方などを定義した構造体)
HumanDescription humanDesc = new HumanDescription();
humanDesc.human = humanBones.ToArray();
humanDesc.skeleton = GetTransforms(transform).ToArray();
humanDesc.upperArmTwist = 0.5f;
humanDesc.lowerArmTwist = 0.5f;
humanDesc.upperLegTwist = 0.5f;
humanDesc.lowerLegTwist = 0.5f;
humanDesc.armStretch = 0.05f;
humanDesc.legStretch = 0.05f;
humanDesc.feetSpacing = 0.05f;
// アバターオブジェクトをビルド
Avatar avatar = AvatarBuilder.BuildHumanAvatar(gameObject, humanDesc);
avatar.name = gameObject.name + AvatarNameTail;
if (!avatar.isValid || !avatar.isHuman)
{
UnityEngine.Debug.Log("Error when building avatar");
return false;
}
animator = gameObject.AddComponent<Animator>();
animator.avatar = avatar;
animator.applyRootMotion = true;
animator.runtimeAnimatorController = RuntimeAnimatorController;
return true;
}
private List<SkeletonBone> GetTransforms(Transform t)
{
SkeletonBone skeletonBone = new SkeletonBone()
{
name = t.name,
position = t.localPosition,
rotation = t.localRotation,
scale = t.localScale
};
List<SkeletonBone> singleParentFamily = new List<SkeletonBone>() { skeletonBone };
foreach (Transform childT in t)
{
singleParentFamily.AddRange(GetTransforms(childT));
}
return singleParentFamily;
}
private async Task<bool> FixBoneWeight()
{
return await FixBoneWeight(skinnedMeshRenderer);
}
private async Task<bool> FixBoneWeight(SkinnedMeshRenderer skinnedMeshRenderer)
{
if (skinnedMeshRenderer == null)
{
UnityEngine.Debug.Log("No SkinnedMeshRenderer.");
return false;
}
if (skinnedMeshRenderer.sharedMesh == null)
{
UnityEngine.Debug.Log("No SharedMesh.");
return false;
}
Transform[] bones = skinnedMeshRenderer.bones;
string[] boneNames = (from t in bones select t.name).ToArray();
BoneWeight[] fixedBoneWeights = skinnedMeshRenderer.sharedMesh.boneWeights;
int vertexCount = skinnedMeshRenderer.sharedMesh.vertexCount;
await Task.Run(() =>
{
for (int i = 0; i < vertexCount; i++)
{
if (model.Alt_OriginalBoneDictionary.ContainsKey(bones[fixedBoneWeights[i].boneIndex0]))
{
fixedBoneWeights[i].boneIndex0
= model.OriginalBone_IndexDictionary[model.Alt_OriginalBoneDictionary[bones[fixedBoneWeights[i].boneIndex0]]];
}
if (model.Alt_OriginalBoneDictionary.ContainsKey(bones[fixedBoneWeights[i].boneIndex1]))
{
fixedBoneWeights[i].boneIndex1
= model.OriginalBone_IndexDictionary[model.Alt_OriginalBoneDictionary[bones[fixedBoneWeights[i].boneIndex1]]];
}
if (model.Alt_OriginalBoneDictionary.ContainsKey(bones[fixedBoneWeights[i].boneIndex2]))
{
fixedBoneWeights[i].boneIndex2
= model.OriginalBone_IndexDictionary[model.Alt_OriginalBoneDictionary[bones[fixedBoneWeights[i].boneIndex2]]];
}
if (model.Alt_OriginalBoneDictionary.ContainsKey(bones[fixedBoneWeights[i].boneIndex3]))
{
fixedBoneWeights[i].boneIndex3
= model.OriginalBone_IndexDictionary[model.Alt_OriginalBoneDictionary[bones[fixedBoneWeights[i].boneIndex3]]];
}
if (MMDModel.Alt_OriginalNameDictionary.ContainsKey(boneNames[fixedBoneWeights[i].boneIndex0]))
{
string originalBoneName = MMDModel.Alt_OriginalNameDictionary[boneNames[fixedBoneWeights[i].boneIndex0]];
if (model.OriginalBone_IndexDictionary.ContainsKey(humanBoneDictionary[originalBoneName]))
{
fixedBoneWeights[i].boneIndex0 = model.OriginalBone_IndexDictionary[humanBoneDictionary[originalBoneName]];
}
}
if (MMDModel.Alt_OriginalNameDictionary.ContainsKey(boneNames[fixedBoneWeights[i].boneIndex1]))
{
string originalBoneName = MMDModel.Alt_OriginalNameDictionary[boneNames[fixedBoneWeights[i].boneIndex1]];
if (model.OriginalBone_IndexDictionary.ContainsKey(humanBoneDictionary[originalBoneName]))
{
fixedBoneWeights[i].boneIndex1 = model.OriginalBone_IndexDictionary[humanBoneDictionary[originalBoneName]];
}
}
if (MMDModel.Alt_OriginalNameDictionary.ContainsKey(boneNames[fixedBoneWeights[i].boneIndex2]))
{
string originalBoneName = MMDModel.Alt_OriginalNameDictionary[boneNames[fixedBoneWeights[i].boneIndex2]];
if (model.OriginalBone_IndexDictionary.ContainsKey(humanBoneDictionary[originalBoneName]))
{
fixedBoneWeights[i].boneIndex2 = model.OriginalBone_IndexDictionary[humanBoneDictionary[originalBoneName]];
}
}
if (MMDModel.Alt_OriginalNameDictionary.ContainsKey(boneNames[fixedBoneWeights[i].boneIndex3]))
{
string originalBoneName = MMDModel.Alt_OriginalNameDictionary[boneNames[fixedBoneWeights[i].boneIndex3]];
if (model.OriginalBone_IndexDictionary.ContainsKey(humanBoneDictionary[originalBoneName]))
{
fixedBoneWeights[i].boneIndex3 = model.OriginalBone_IndexDictionary[humanBoneDictionary[originalBoneName]];
}
}
}
});
skinnedMeshRenderer.sharedMesh.boneWeights = fixedBoneWeights;
return true;
}
private Dictionary<string, Transform> MakeHumanBoneDictionary(Transform rootTransform, string[] humanBonesContained)
{
Dictionary<string, Transform> humanBoneDictionary = new Dictionary<string, Transform>();
Queue queue = new Queue();
queue.Enqueue(rootTransform);
while (queue.Count != 0)
{
Transform peek = queue.Peek() as Transform;
if (MMDModel.Unity_MMDBoneNameDictionary.ContainsValue(peek.name) && !humanBoneDictionary.ContainsKey(peek.name))
{
humanBoneDictionary.Add(peek.name, peek);
}
if (humanBonesContained.All(x => x != null && humanBoneDictionary.ContainsKey(x)))
{
break;
}
foreach (Transform childT in (queue.Dequeue() as Transform))
{
queue.Enqueue(childT);
}
}
return humanBoneDictionary;
}
private Dictionary<string, Transform> MakeHumanBoneDictionary(Transform rootTransform)
{
string[] allBones = (from boneName in HumanTrait.BoneName select MMDModel.Unity_MMDBoneNameDictionary[boneName]).ToArray();
return MakeHumanBoneDictionary(rootTransform, allBones);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: aeeb8df58d0fdc04dbcf0663109f4148
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a260ddf6d9b05734fa2dad314acaad9a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,197 @@
using System;
using System.IO;
using UnityEngine;
namespace LibMMD.Unity3D.ImageLoader
{
public class BitmapLoader
{
/* BMPPallete: pallete for BMP */
private struct BmpPallete {
public byte B;
public byte G;
public byte R;
public byte A;
};
/* BMPHeader: header for BMP */
private struct BmpHeader {
public ushort BfType;
public uint BfSize;
public ushort BfReserved1;
public ushort BfReserved2;
public uint BfOffBits;
}
/* BMPInfo: info for BMP */
struct BmpInfo {
public uint BiSize;
public int BiWidth;
public int BiHeight;
public ushort BiPlanes;
public ushort BiBitCount;
public uint BiCompression;
public uint BiSizeImage;
public uint BiXPelsPerMeter;
public uint BiYPelsPerMeter;
public uint BiClrUsed;
public uint BiClrImportant;
};
public static TextureImage LoadFromFile(string path)
{
var data = File.ReadAllBytes (path);
if (data [0] != 'B' || data [1] != 'M') {
return null;
}
var offset = 0;
var bmpHeader = ReadBmpHeader (data, ref offset);
var bodyOffset = bmpHeader.BfOffBits;
var len = BitConverter.ToInt64 (data, offset);
if (len == 12) {
return null;
}
var bmpinfo = ReadBmpInfo (data, ref offset);
var width = bmpinfo.BiWidth;
var reversed = false;
int height;
if (bmpinfo.BiHeight < 0) {
height = -bmpinfo.BiHeight;
} else {
height = bmpinfo.BiHeight;
reversed = true;
}
var bit = bmpinfo.BiBitCount;
if (bmpinfo.BiCompression != 0) {
Debug.LogWarningFormat ("not support compressed bitmap {0}", bmpinfo.BiCompression);
return null;
}
Color[] pallette = null;
if (bit <= 8) {
pallette = ReadBmpPallete (data, ref offset, GetPalletteColorCount (bmpinfo.BiClrUsed, bit));
}
var pixels = ReadBmpBody (data, (int) bodyOffset, width, height, bit, reversed, pallette);
return pixels == null ? null : new TextureImage (width, height, pixels);
}
private static BmpHeader ReadBmpHeader(byte[] data, ref int offset) {
var ret = new BmpHeader
{
BfType = ByteArrayReader.ReadUShort(data, ref offset),
BfSize = ByteArrayReader.ReadUInt(data, ref offset),
BfReserved1 = ByteArrayReader.ReadUShort(data, ref offset),
BfReserved2 = ByteArrayReader.ReadUShort(data, ref offset),
BfOffBits = ByteArrayReader.ReadUInt(data, ref offset)
};
return ret;
}
private static BmpInfo ReadBmpInfo(byte[] data, ref int offset) {
var ret = new BmpInfo
{
BiSize = ByteArrayReader.ReadUInt(data, ref offset),
BiWidth = ByteArrayReader.ReadInt(data, ref offset),
BiHeight = ByteArrayReader.ReadInt(data, ref offset),
BiPlanes = ByteArrayReader.ReadUShort(data, ref offset),
BiBitCount = ByteArrayReader.ReadUShort(data, ref offset),
BiCompression = ByteArrayReader.ReadUInt(data, ref offset),
BiSizeImage = ByteArrayReader.ReadUInt(data, ref offset),
BiXPelsPerMeter = ByteArrayReader.ReadUInt(data, ref offset),
BiYPelsPerMeter = ByteArrayReader.ReadUInt(data, ref offset),
BiClrUsed = ByteArrayReader.ReadUInt(data, ref offset),
BiClrImportant = ByteArrayReader.ReadUInt(data, ref offset)
};
return ret;
}
private static Color[] ReadBmpPallete(byte[] data, ref int offset, uint count) {
var ret = new Color[count];
const float maxColorVal = 255.0f;
for (uint i = 0; i < count; i++) {
ret [i].b = data [offset] / maxColorVal;
ret [i].g = data [offset + 1] / maxColorVal;
ret [i].r = data [offset + 2] / maxColorVal;
ret [i].a = data [offset + 3] / maxColorVal;
offset += 4;
}
return ret;
}
private static uint GetPalletteColorCount(uint nClr, ushort nBit) {
if (nClr != 0) {
return nClr;
}
return ((uint)1) >> nBit;
}
private static Color[] ReadBmpBody(byte[] data, int offset, int width, int height,int bit, bool reversed, Color[] pallete) {
const float maxByte = 255.0f;
var ret = new Color[width * height];
var lineByte = (width * bit) / 8;
if ((lineByte % 4) != 0) {
lineByte = ((lineByte / 4) + 1) * 4; //force 4-byte alignment
}
var t = 0;
for (var h = 0; h < height; h++) {
int tl;
if (reversed) {
tl = offset + h * lineByte;
} else {
tl = offset + (height - h - 1) * lineByte;
}
for (var w = 0; w < width; w++)
{
byte ci;
switch (bit) {
case 1: {
ci = data[tl + w / 8];
var mod = w % 8;
var bitmask = (mod == 0) ? 0x80 : (0x80 >> mod);
ci = (ci & bitmask) != 0 ? (byte)1 : (byte)0;
ret[t] = pallete[ci];
t++;
}
break;
case 4: {
ci = data [tl + w / 2];
if (w % 2 == 0)
ci = (byte)((ci >> 4) & 0x0f);
else
ci = (byte)(ci & 0x0f);
ret[t] = pallete[ci];
t++;
}
break;
case 8: {
ci = data [tl + w];
ret[t] = pallete[ci];
t++;
}
break;
case 24:
/* BGR -> RGB */
ret [t].r = data [tl + w * 3 + 2] / maxByte;
ret [t].g = data [tl + w * 3 + 1] / maxByte;
ret [t].b = data [tl + w * 3] / maxByte;
ret [t].a = 1.0f;
t++;
break;
case 32:
ret [t].r = data [tl + w * 4 + 2] / maxByte;
ret [t].g = data [tl + w * 4 + 1] / maxByte;
ret [t].b = data [tl + w * 4] / maxByte;
//ret [t].a = data [tl + w * 4 + 3] / maxByte; //有些bmp会变成全透明的orz
ret [t].a = 1.0f;
t++;
break;
default:
return null;
}
}
}
return ret;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ae95b04f1bc41da4abfa6ba6aacbd19a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,743 @@
/*从 https://github.com/npedotnet/DDSReader 译成C#代码*/
namespace LibMMD.Unity3D.ImageLoader
{
public class DdsLoader
{
public struct DdsOrder
{
public int RedShift;
public int GreenShift;
public int BlueShift;
public int AlphaShift;
}
public static readonly DdsOrder DdsReaderArgb;
public static readonly DdsOrder DdsReaderAbgr;
static DdsLoader()
{
DdsReaderArgb.RedShift = 16;
DdsReaderArgb.GreenShift = 8;
DdsReaderArgb.BlueShift = 0;
DdsReaderArgb.AlphaShift = 24;
DdsReaderAbgr.RedShift = 0;
DdsReaderAbgr.GreenShift = 8;
DdsReaderAbgr.BlueShift = 16;
DdsReaderAbgr.AlphaShift = 24;
}
public static int DdsGetHeight(byte[] buffer)
{
return (buffer[12] & 0xFF) | (buffer[13] & 0xFF) << 8 | (buffer[14] & 0xFF) << 16 |
(buffer[15] & 0xFF) << 24;
}
public static int DdsGetWidth(byte[] buffer)
{
return (buffer[16] & 0xFF) | (buffer[17] & 0xFF) << 8 | (buffer[18] & 0xFF) << 16 |
(buffer[19] & 0xFF) << 24;
}
public static int DdsGetMipmap(byte[] buffer)
{
return (buffer[28] & 0xFF) | (buffer[29] & 0xFF) << 8 | (buffer[30] & 0xFF) << 16 |
(buffer[31] & 0xFF) << 24;
}
public static int DdsGetPixelFormatFlags(byte[] buffer)
{
return (buffer[80] & 0xFF) | (buffer[81] & 0xFF) << 8 | (buffer[82] & 0xFF) << 16 |
(buffer[83] & 0xFF) << 24;
}
public static int DdsGetFourCc(byte[] buffer)
{
return (buffer[84] & 0xFF) << 24 | (buffer[85] & 0xFF) << 16 | (buffer[86] & 0xFF) << 8 |
(buffer[87] & 0xFF);
}
public static int DdsGetBitCount(byte[] buffer)
{
return (buffer[88] & 0xFF) | (buffer[89] & 0xFF) << 8 | (buffer[90] & 0xFF) << 16 |
(buffer[91] & 0xFF) << 24;
}
public static int DdsGetRedMask(byte[] buffer)
{
return (buffer[92] & 0xFF) | (buffer[93] & 0xFF) << 8 | (buffer[94] & 0xFF) << 16 |
(buffer[95] & 0xFF) << 24;
}
public static int DdsGetGreenMask(byte[] buffer)
{
return (buffer[96] & 0xFF) | (buffer[97] & 0xFF) << 8 | (buffer[98] & 0xFF) << 16 |
(buffer[99] & 0xFF) << 24;
}
public static int DdsGetBlueMask(byte[] buffer)
{
return (buffer[100] & 0xFF) | (buffer[101] & 0xFF) << 8 | (buffer[102] & 0xFF) << 16 |
(buffer[103] & 0xFF) << 24;
}
public static int DdsGetAlphaMask(byte[] buffer)
{
return (buffer[104] & 0xFF) | (buffer[105] & 0xFF) << 8 | (buffer[106] & 0xFF) << 16 |
(buffer[107] & 0xFF) << 24;
}
// Image Type
private const int Dxt1 = 0x44585431;
private const int Dxt2 = 0x44585432;
private const int Dxt3 = 0x44585433;
private const int Dxt4 = 0x44585434;
private const int Dxt5 = 0x44585435;
private const int A1R5G5B5 = (1 << 16) | 2;
private const int X1R5G5B5 = (2 << 16) | 2;
private const int A4R4G4B4 = (3 << 16) | 2;
private const int X4R4G4B4 = (4 << 16) | 2;
private const int R5G6B5 = (5 << 16) | 2;
private const int R8G8B8 = (1 << 16) | 3;
private const int A8B8G8R8 = (1 << 16) | 4;
private const int X8B8G8R8 = (2 << 16) | 4;
private const int A8R8G8B8 = (3 << 16) | 4;
private const int X8R8G8B8 = (4 << 16) | 4;
// RGBA Masks
private static readonly int[] A1R5G5B5Masks = {0x7C00, 0x03E0, 0x001F, 0x8000};
private static readonly int[] X1R5G5B5Masks = {0x7C00, 0x03E0, 0x001F, 0x0000};
private static readonly int[] A4R4G4B4Masks = {0x0F00, 0x00F0, 0x000F, 0xF000};
private static readonly int[] X4R4G4B4Masks = {0x0F00, 0x00F0, 0x000F, 0x0000};
private static readonly int[] R5G6B5Masks = {0xF800, 0x07E0, 0x001F, 0x0000};
private static readonly int[] R8G8B8Masks = {0xFF0000, 0x00FF00, 0x0000FF, 0x000000};
private static readonly int[] A8B8G8R8Masks = {0x000000FF, 0x0000FF00, 0x00FF0000, unchecked((int) 0xFF000000)};
private static readonly int[] X8B8G8R8Masks = {0x000000FF, 0x0000FF00, 0x00FF0000, 0x00000000};
private static readonly int[] A8R8G8B8Masks = {0x00FF0000, 0x0000FF00, 0x000000FF, unchecked((int) 0xFF000000)};
private static readonly int[] X8R8G8B8Masks = {0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000};
// BIT4 = 17 * index;
private static readonly int[] Bit5 =
{
0, 8, 16, 25, 33, 41, 49, 58, 66, 74, 82, 90, 99, 107, 115, 123, 132, 140, 148, 156, 165, 173, 181, 189,
197, 206, 214, 222, 230, 239, 247, 255
};
private static readonly int[] Bit6 =
{
0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 45, 49, 53, 57, 61, 65, 69, 73, 77, 81, 85, 89, 93, 97, 101, 105,
109, 113, 117, 121, 125, 130, 134, 138, 142, 146, 150, 154, 158, 162, 166, 170, 174, 178, 182, 186, 190,
194, 198, 202, 206, 210, 215, 219, 223, 227, 231, 235, 239, 243, 247, 251, 255
};
public static int[] DdsRead(byte[] buffer, DdsOrder order, int mipmapLevel)
{
// header
var width = DdsGetWidth(buffer);
var height = DdsGetHeight(buffer);
var mipmap = DdsGetMipmap(buffer);
// type
var type = DdsGetType(buffer);
if (type == 0) return null;
// offset
var offset = 128;
if (mipmapLevel > 0 && mipmapLevel < mipmap)
{
for (var i = 0; i < mipmapLevel; i++)
{
switch (type)
{
case Dxt1:
offset += 8 * ((width + 3) / 4) * ((height + 3) / 4);
break;
case Dxt2:
case Dxt3:
case Dxt4:
case Dxt5:
offset += 16 * ((width + 3) / 4) * ((height + 3) / 4);
break;
case A1R5G5B5:
case X1R5G5B5:
case A4R4G4B4:
case X4R4G4B4:
case R5G6B5:
case R8G8B8:
case A8B8G8R8:
case X8B8G8R8:
case A8R8G8B8:
case X8R8G8B8:
offset += (type & 0xFF) * width * height;
break;
}
width /= 2;
height /= 2;
}
if (width <= 0) width = 1;
if (height <= 0) height = 1;
}
// System.out.println("Width:" + width + ", Height:" + height + ", Mipmap: " + mipmap + ", Offset:" + offset + ", Type:" + type);
{
int[] pixels = null;
switch (type)
{
case Dxt1:
pixels = DdsDecodeDxt1(width, height, offset, buffer, order);
break;
case Dxt2:
pixels = DdsDecodeDxt2(width, height, offset, buffer, order);
break;
case Dxt3:
pixels = DdsDecodeDxt3(width, height, offset, buffer, order);
break;
case Dxt4:
pixels = DdsDecodeDxt4(width, height, offset, buffer, order);
break;
case Dxt5:
pixels = DdsDecodeDxt5(width, height, offset, buffer, order);
break;
case A1R5G5B5:
pixels = DdsReadA1R5G5B5(width, height, offset, buffer, order);
break;
case X1R5G5B5:
pixels = DdsReadX1R5G5B5(width, height, offset, buffer, order);
break;
case A4R4G4B4:
pixels = DdsReadA4R4G4B4(width, height, offset, buffer, order);
break;
case X4R4G4B4:
pixels = DdsReadX4R4G4B4(width, height, offset, buffer, order);
break;
case R5G6B5:
pixels = DdsReadR5G6B5(width, height, offset, buffer, order);
break;
case R8G8B8:
pixels = DdsReadR8G8B8(width, height, offset, buffer, order);
break;
case A8B8G8R8:
pixels = DdsReadA8B8G8R8(width, height, offset, buffer, order);
break;
case X8B8G8R8:
pixels = DdsReadX8B8G8R8(width, height, offset, buffer, order);
break;
case A8R8G8B8:
pixels = DdsReadA8R8G8B8(width, height, offset, buffer, order);
break;
case X8R8G8B8:
pixels = DdsReadX8R8G8B8(width, height, offset, buffer, order);
break;
}
return pixels;
}
}
private static int DdsGetType(byte[] buffer)
{
var type = 0;
var flags = DdsGetPixelFormatFlags(buffer);
if ((flags & 0x04) != 0)
{
// DXT
type = DdsGetFourCc(buffer);
}
else if ((flags & 0x40) != 0)
{
// RGB
var bitCount = DdsGetBitCount(buffer);
var redMask = DdsGetRedMask(buffer);
var greenMask = DdsGetGreenMask(buffer);
var blueMask = DdsGetBlueMask(buffer);
var alphaMask = ((flags & 0x01) != 0) ? DdsGetAlphaMask(buffer) : 0; // 0x01 alpha
if (bitCount == 16)
{
if (redMask == A1R5G5B5Masks[0] && greenMask == A1R5G5B5Masks[1] && blueMask == A1R5G5B5Masks[2] &&
alphaMask == A1R5G5B5Masks[3])
{
// A1R5G5B5
type = A1R5G5B5;
}
else if (redMask == X1R5G5B5Masks[0] && greenMask == X1R5G5B5Masks[1] &&
blueMask == X1R5G5B5Masks[2] && alphaMask == X1R5G5B5Masks[3])
{
// X1R5G5B5
type = X1R5G5B5;
}
else if (redMask == A4R4G4B4Masks[0] && greenMask == A4R4G4B4Masks[1] &&
blueMask == A4R4G4B4Masks[2] && alphaMask == A4R4G4B4Masks[3])
{
// A4R4G4B4
type = A4R4G4B4;
}
else if (redMask == X4R4G4B4Masks[0] && greenMask == X4R4G4B4Masks[1] &&
blueMask == X4R4G4B4Masks[2] && alphaMask == X4R4G4B4Masks[3])
{
// X4R4G4B4
type = X4R4G4B4;
}
else if (redMask == R5G6B5Masks[0] && greenMask == R5G6B5Masks[1] && blueMask == R5G6B5Masks[2] &&
alphaMask == R5G6B5Masks[3])
{
// R5G6B5
type = R5G6B5;
}
else
{
// Unsupported 16bit RGB image
}
}
else if (bitCount == 24)
{
if (redMask == R8G8B8Masks[0] && greenMask == R8G8B8Masks[1] && blueMask == R8G8B8Masks[2] &&
alphaMask == R8G8B8Masks[3])
{
// R8G8B8
type = R8G8B8;
}
else
{
// Unsupported 24bit RGB image
}
}
else if (bitCount == 32)
{
if (redMask == A8B8G8R8Masks[0] && greenMask == A8B8G8R8Masks[1] && blueMask == A8B8G8R8Masks[2] &&
alphaMask == A8B8G8R8Masks[3])
{
// A8B8G8R8
type = A8B8G8R8;
}
else if (redMask == X8B8G8R8Masks[0] && greenMask == X8B8G8R8Masks[1] &&
blueMask == X8B8G8R8Masks[2] && alphaMask == X8B8G8R8Masks[3])
{
// X8B8G8R8
type = X8B8G8R8;
}
else if (redMask == A8R8G8B8Masks[0] && greenMask == A8R8G8B8Masks[1] &&
blueMask == A8R8G8B8Masks[2] && alphaMask == A8R8G8B8Masks[3])
{
// A8R8G8B8
type = A8R8G8B8;
}
else if (redMask == X8R8G8B8Masks[0] && greenMask == X8R8G8B8Masks[1] &&
blueMask == X8R8G8B8Masks[2] && alphaMask == X8R8G8B8Masks[3])
{
// X8R8G8B8
type = X8R8G8B8;
}
else
{
// Unsupported 32bit RGB image
}
}
}
else
{
// YUV or LUMINANCE image
}
return type;
}
private static int[] DdsDecodeDxt1(int width, int height, int offset, byte[] buffer, DdsOrder order)
{
var pixels = new int[4 * width * height];
var index = offset;
var w = (width + 3) / 4;
var h = (height + 3) / 4;
for (var i = 0; i < h; i++)
{
for (var j = 0; j < w; j++)
{
var c0 = (buffer[index] & 0xFF) | (buffer[index + 1] & 0xFF) << 8;
index += 2;
var c1 = (buffer[index] & 0xFF) | (buffer[index + 1] & 0xFF) << 8;
index += 2;
for (var k = 0; k < 4; k++)
{
if (4 * i + k >= height) break;
var t0 = (buffer[index] & 0x03);
var t1 = (buffer[index] & 0x0C) >> 2;
var t2 = (buffer[index] & 0x30) >> 4;
var t3 = (buffer[index++] & 0xC0) >> 6;
pixels[4 * width * i + 4 * j + width * k + 0] = DdsGetDxtColor(c0, c1, 0xFF, t0, order);
if (4 * j + 1 >= width) continue;
pixels[4 * width * i + 4 * j + width * k + 1] = DdsGetDxtColor(c0, c1, 0xFF, t1, order);
if (4 * j + 2 >= width) continue;
pixels[4 * width * i + 4 * j + width * k + 2] = DdsGetDxtColor(c0, c1, 0xFF, t2, order);
if (4 * j + 3 >= width) continue;
pixels[4 * width * i + 4 * j + width * k + 3] = DdsGetDxtColor(c0, c1, 0xFF, t3, order);
}
}
}
return pixels;
}
private static int[] DdsDecodeDxt2(int width, int height, int offset, byte[] buffer, DdsOrder order)
{
return DdsDecodeDxt3(width, height, offset, buffer, order);
}
private static int[] DdsDecodeDxt3(int width, int height, int offset, byte[] buffer, DdsOrder order)
{
var pixels = new int [4 * width * height];
var index = offset;
var w = (width + 3) / 4;
var h = (height + 3) / 4;
var alphaTable = new int[16];
for (var i = 0; i < h; i++)
{
for (var j = 0; j < w; j++)
{
// create alpha table(4bit to 8bit)
for (var k = 0; k < 4; k++)
{
var a0 = buffer[index++] & 0xFF;
var a1 = buffer[index++] & 0xFF;
// 4bit alpha to 8bit alpha
alphaTable[4 * k + 0] = 17 * ((a0 & 0xF0) >> 4);
alphaTable[4 * k + 1] = 17 * (a0 & 0x0F);
alphaTable[4 * k + 2] = 17 * ((a1 & 0xF0) >> 4);
alphaTable[4 * k + 3] = 17 * (a1 & 0x0F);
}
var c0 = (buffer[index] & 0xFF) | (buffer[index + 1] & 0xFF) << 8;
index += 2;
var c1 = (buffer[index] & 0xFF) | (buffer[index + 1] & 0xFF) << 8;
index += 2;
for (var k = 0; k < 4; k++)
{
if (4 * i + k >= height) break;
var t0 = (buffer[index] & 0x03);
var t1 = (buffer[index] & 0x0C) >> 2;
var t2 = (buffer[index] & 0x30) >> 4;
var t3 = (buffer[index++] & 0xC0) >> 6;
pixels[4 * width * i + 4 * j + width * k + 0] =
DdsGetDxtColor(c0, c1, alphaTable[4 * k + 0], t0, order);
if (4 * j + 1 >= width) continue;
pixels[4 * width * i + 4 * j + width * k + 1] =
DdsGetDxtColor(c0, c1, alphaTable[4 * k + 1], t1, order);
if (4 * j + 2 >= width) continue;
pixels[4 * width * i + 4 * j + width * k + 2] =
DdsGetDxtColor(c0, c1, alphaTable[4 * k + 2], t2, order);
if (4 * j + 3 >= width) continue;
pixels[4 * width * i + 4 * j + width * k + 3] =
DdsGetDxtColor(c0, c1, alphaTable[4 * k + 3], t3, order);
}
}
}
return pixels;
}
private static int[] DdsDecodeDxt4(int width, int height, int offset, byte[] buffer, DdsOrder order)
{
return DdsDecodeDxt5(width, height, offset, buffer, order);
}
private static int[] DdsDecodeDxt5(int width, int height, int offset, byte[] buffer, DdsOrder order)
{
var pixels = new int [4 * width * height];
var index = offset;
var w = (width + 3) / 4;
var h = (height + 3) / 4;
var alphaTable = new int[16];
for (var i = 0; i < h; i++)
{
for (var j = 0; j < w; j++)
{
// create alpha table
var a0 = buffer[index++] & 0xFF;
var a1 = buffer[index++] & 0xFF;
var b0 = (buffer[index] & 0xFF) | (buffer[index + 1] & 0xFF) << 8 |
(buffer[index + 2] & 0xFF) << 16;
index += 3;
var b1 = (buffer[index] & 0xFF) | (buffer[index + 1] & 0xFF) << 8 |
(buffer[index + 2] & 0xFF) << 16;
index += 3;
alphaTable[0] = b0 & 0x07;
alphaTable[1] = (b0 >> 3) & 0x07;
alphaTable[2] = (b0 >> 6) & 0x07;
alphaTable[3] = (b0 >> 9) & 0x07;
alphaTable[4] = (b0 >> 12) & 0x07;
alphaTable[5] = (b0 >> 15) & 0x07;
alphaTable[6] = (b0 >> 18) & 0x07;
alphaTable[7] = (b0 >> 21) & 0x07;
alphaTable[8] = b1 & 0x07;
alphaTable[9] = (b1 >> 3) & 0x07;
alphaTable[10] = (b1 >> 6) & 0x07;
alphaTable[11] = (b1 >> 9) & 0x07;
alphaTable[12] = (b1 >> 12) & 0x07;
alphaTable[13] = (b1 >> 15) & 0x07;
alphaTable[14] = (b1 >> 18) & 0x07;
alphaTable[15] = (b1 >> 21) & 0x07;
var c0 = (buffer[index] & 0xFF) | (buffer[index + 1] & 0xFF) << 8;
index += 2;
var c1 = (buffer[index] & 0xFF) | (buffer[index + 1] & 0xFF) << 8;
index += 2;
for (var k = 0; k < 4; k++)
{
if (4 * i + k >= height) break;
var t0 = buffer[index] & 0x03;
var t1 = (buffer[index] & 0x0C) >> 2;
var t2 = (buffer[index] & 0x30) >> 4;
var t3 = (buffer[index++] & 0xC0) >> 6;
pixels[4 * width * i + 4 * j + width * k + 0] = DdsGetDxtColor(c0, c1,
DdsGetDxt5Alpha(a0, a1, alphaTable[4 * k + 0]), t0, order);
if (4 * j + 1 >= width) continue;
pixels[4 * width * i + 4 * j + width * k + 1] = DdsGetDxtColor(c0, c1,
DdsGetDxt5Alpha(a0, a1, alphaTable[4 * k + 1]), t1, order);
if (4 * j + 2 >= width) continue;
pixels[4 * width * i + 4 * j + width * k + 2] = DdsGetDxtColor(c0, c1,
DdsGetDxt5Alpha(a0, a1, alphaTable[4 * k + 2]), t2, order);
if (4 * j + 3 >= width) continue;
pixels[4 * width * i + 4 * j + width * k + 3] = DdsGetDxtColor(c0, c1,
DdsGetDxt5Alpha(a0, a1, alphaTable[4 * k + 3]), t3, order);
}
}
}
return pixels;
}
private static int[] DdsReadA1R5G5B5(int width, int height, int offset, byte[] buffer, DdsOrder order)
{
var index = offset;
var pixels = new int[4 * width * height];
for (var i = 0; i < height * width; i++)
{
var rgba = (buffer[index] & 0xFF) | (buffer[index + 1] & 0xFF) << 8;
index += 2;
var r = Bit5[(rgba & A1R5G5B5Masks[0]) >> 10];
var g = Bit5[(rgba & A1R5G5B5Masks[1]) >> 5];
var b = Bit5[rgba & A1R5G5B5Masks[2]];
var a = 255 * ((rgba & A1R5G5B5Masks[3]) >> 15);
pixels[i] = (a << order.AlphaShift) | (r << order.RedShift) | (g << order.GreenShift) |
(b << order.BlueShift);
}
return pixels;
}
private static int[] DdsReadX1R5G5B5(int width, int height, int offset, byte[] buffer, DdsOrder order)
{
var index = offset;
var pixels = new int [4 * width * height];
for (var i = 0; i < height * width; i++)
{
var rgba = (buffer[index] & 0xFF) | (buffer[index + 1] & 0xFF) << 8;
index += 2;
var r = Bit5[(rgba & X1R5G5B5Masks[0]) >> 10];
var g = Bit5[(rgba & X1R5G5B5Masks[1]) >> 5];
var b = Bit5[(rgba & X1R5G5B5Masks[2])];
var a = 255;
pixels[i] = (a << order.AlphaShift) | (r << order.RedShift) | (g << order.GreenShift) |
(b << order.BlueShift);
}
return pixels;
}
private static int[] DdsReadA4R4G4B4(int width, int height, int offset, byte[] buffer, DdsOrder order)
{
var index = offset;
var pixels = new int [4 * width * height];
for (var i = 0; i < height * width; i++)
{
var rgba = (buffer[index] & 0xFF) | (buffer[index + 1] & 0xFF) << 8;
index += 2;
var r = 17 * ((rgba & A4R4G4B4Masks[0]) >> 8);
var g = 17 * ((rgba & A4R4G4B4Masks[1]) >> 4);
var b = 17 * (rgba & A4R4G4B4Masks[2]);
var a = 17 * ((rgba & A4R4G4B4Masks[3]) >> 12);
pixels[i] = (a << order.AlphaShift) | (r << order.RedShift) | (g << order.GreenShift) |
(b << order.BlueShift);
}
return pixels;
}
private static int[] DdsReadX4R4G4B4(int width, int height, int offset, byte[] buffer, DdsOrder order)
{
var index = offset;
var pixels = new int [4 * width * height];
for (var i = 0; i < height * width; i++)
{
var rgba = (buffer[index] & 0xFF) | (buffer[index + 1] & 0xFF) << 8;
index += 2;
var r = 17 * ((rgba & A4R4G4B4Masks[0]) >> 8);
var g = 17 * ((rgba & A4R4G4B4Masks[1]) >> 4);
var b = 17 * (rgba & A4R4G4B4Masks[2]);
const int a = 255;
pixels[i] = (a << order.AlphaShift) | (r << order.RedShift) | (g << order.GreenShift) |
(b << order.BlueShift);
}
return pixels;
}
private static int[] DdsReadR5G6B5(int width, int height, int offset, byte[] buffer, DdsOrder order)
{
var index = offset;
var pixels = new int [4 * width * height];
for (var i = 0; i < height * width; i++)
{
var rgba = (buffer[index] & 0xFF) | (buffer[index + 1] & 0xFF) << 8;
index += 2;
var r = Bit5[((rgba & R5G6B5Masks[0]) >> 11)];
var g = Bit6[((rgba & R5G6B5Masks[1]) >> 5)];
var b = Bit5[((rgba & R5G6B5Masks[2]))];
const int a = 255;
pixels[i] = (a << order.AlphaShift) | (r << order.RedShift) | (g << order.GreenShift) |
(b << order.BlueShift);
}
return pixels;
}
private static int[] DdsReadR8G8B8(int width, int height, int offset, byte[] buffer, DdsOrder order)
{
var index = offset;
var pixels = new int [4 * width * height];
for (var i = 0; i < height * width; i++)
{
var b = buffer[index++] & 0xFF;
var g = buffer[index++] & 0xFF;
var r = buffer[index++] & 0xFF;
var a = 255;
pixels[i] = (a << order.AlphaShift) | (r << order.RedShift) | (g << order.GreenShift) |
(b << order.BlueShift);
}
return pixels;
}
private static int[] DdsReadA8B8G8R8(int width, int height, int offset, byte[] buffer, DdsOrder order)
{
var index = offset;
var pixels = new int [4 * width * height];
for (var i = 0; i < height * width; i++)
{
var r = buffer[index++] & 0xFF;
var g = buffer[index++] & 0xFF;
var b = buffer[index++] & 0xFF;
var a = buffer[index++] & 0xFF;
pixels[i] = (a << order.AlphaShift) | (r << order.RedShift) | (g << order.GreenShift) |
(b << order.BlueShift);
}
return pixels;
}
private static int[] DdsReadX8B8G8R8(int width, int height, int offset, byte[] buffer, DdsOrder order)
{
var index = offset;
int[] pixels = new int [4 * width * height];
for (int i = 0; i < height * width; i++)
{
var r = buffer[index++] & 0xFF;
var g = buffer[index++] & 0xFF;
var b = buffer[index++] & 0xFF;
var a = 255;
index++;
pixels[i] = (a << order.AlphaShift) | (r << order.RedShift) | (g << order.GreenShift) |
(b << order.BlueShift);
}
return pixels;
}
private static int[] DdsReadA8R8G8B8(int width, int height, int offset, byte[] buffer, DdsOrder order)
{
var index = offset;
int[] pixels = new int [4 * width * height];
for (int i = 0; i < height * width; i++)
{
var b = buffer[index++] & 0xFF;
var g = buffer[index++] & 0xFF;
var r = buffer[index++] & 0xFF;
var a = buffer[index++] & 0xFF;
pixels[i] = (a << order.AlphaShift) | (r << order.RedShift) | (g << order.GreenShift) |
(b << order.BlueShift);
}
return pixels;
}
private static int[] DdsReadX8R8G8B8(int width, int height, int offset, byte[] buffer, DdsOrder order)
{
var index = offset;
int[] pixels = new int [4 * width * height];
for (int i = 0; i < height * width; i++)
{
var b = buffer[index++] & 0xFF;
var g = buffer[index++] & 0xFF;
var r = buffer[index++] & 0xFF;
var a = 255;
index++;
pixels[i] = (a << order.AlphaShift) | (r << order.RedShift) | (g << order.GreenShift) |
(b << order.BlueShift);
}
return pixels;
}
private static int DdsGetDxtColor(int c0, int c1, int a, int t, DdsOrder order)
{
switch (t)
{
case 0: return DdsGetDxtColor1(c0, a, order);
case 1: return DdsGetDxtColor1(c1, a, order);
case 2: return (c0 > c1) ? ddsGetDXTColor2_1(c0, c1, a, order) : ddsGetDXTColor1_1(c0, c1, a, order);
case 3: return (c0 > c1) ? ddsGetDXTColor2_1(c1, c0, a, order) : 0;
}
return 0;
}
private static int ddsGetDXTColor2_1(int c0, int c1, int a, DdsOrder order)
{
// 2*c0/3 + c1/3
var r = (2 * Bit5[(c0 & 0xFC00) >> 11] + Bit5[(c1 & 0xFC00) >> 11]) / 3;
var g = (2 * Bit6[(c0 & 0x07E0) >> 5] + Bit6[(c1 & 0x07E0) >> 5]) / 3;
var b = (2 * Bit5[c0 & 0x001F] + Bit5[c1 & 0x001F]) / 3;
return (a << order.AlphaShift) | (r << order.RedShift) | (g << order.GreenShift) | (b << order.BlueShift);
}
private static int ddsGetDXTColor1_1(int c0, int c1, int a, DdsOrder order)
{
// (c0+c1) / 2
var r = (Bit5[(c0 & 0xFC00) >> 11] + Bit5[(c1 & 0xFC00) >> 11]) / 2;
var g = (Bit6[(c0 & 0x07E0) >> 5] + Bit6[(c1 & 0x07E0) >> 5]) / 2;
var b = (Bit5[c0 & 0x001F] + Bit5[c1 & 0x001F]) / 2;
return (a << order.AlphaShift) | (r << order.RedShift) | (g << order.GreenShift) | (b << order.BlueShift);
}
private static int DdsGetDxtColor1(int c, int a, DdsOrder order)
{
var r = Bit5[(c & 0xFC00) >> 11];
var g = Bit6[(c & 0x07E0) >> 5];
var b = Bit5[(c & 0x001F)];
return (a << order.AlphaShift) | (r << order.RedShift) | (g << order.GreenShift) | (b << order.BlueShift);
}
private static int DdsGetDxt5Alpha(int a0, int a1, int t)
{
if (a0 > a1)
switch (t)
{
case 0: return a0;
case 1: return a1;
case 2: return (6 * a0 + a1) / 7;
case 3: return (5 * a0 + 2 * a1) / 7;
case 4: return (4 * a0 + 3 * a1) / 7;
case 5: return (3 * a0 + 4 * a1) / 7;
case 6: return (2 * a0 + 5 * a1) / 7;
case 7: return (a0 + 6 * a1) / 7;
}
else
switch (t)
{
case 0: return a0;
case 1: return a1;
case 2: return (4 * a0 + a1) / 5;
case 3: return (3 * a0 + 2 * a1) / 5;
case 4: return (2 * a0 + 3 * a1) / 5;
case 5: return (a0 + 4 * a1) / 5;
case 6: return 0;
case 7: return 255;
}
return 0;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fdc931497f191fa4e81c010dee1c43b2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c3917c9113eb16f4a804239cdcbeade2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,37 @@
using UnityEngine;
namespace LibMMD.Unity3D.ImageLoader
{
public class TextureImage
{
private readonly int width;
private readonly int height;
private readonly Color[] pixels;
public int Width {
get {
return width;
}
}
public int Height {
get {
return height;
}
}
public Color[] Pixels {
get {
return pixels;
}
}
public TextureImage (int width, int height, Color[] pixels)
{
this.width = width;
this.height = height;
this.pixels = pixels;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d15bd2e8f26ad1d49a28da77c1ae253d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,626 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using LibMMD.Model;
using LibMMD.Reader;
using UnityEngine;
using System.Threading.Tasks;
namespace LibMMD.Unity3D
{
public class MMDModel : MonoBehaviour
{
public static Dictionary<string, string> Unity_MMDBoneNameDictionary = new Dictionary<string, string>()
{
{"Hips","センター"},
{"LeftUpperLeg","左足"},
{"RightUpperLeg","右足"},
{"LeftLowerLeg","左ひざ"},
{"RightLowerLeg","右ひざ"},
{"LeftFoot","左足首"},
{"RightFoot","右足首"},
{"Spine","上半身"},
{"Chest", null},
{"Neck","首"},
{"Head","頭"},
{ LeftShoulder,"左肩"},
{ RightShoulder,"右肩"},
{ LeftUpperArm,"左腕"},
{ RightUpperArm,"右腕"},
{ LeftLowerArm,"左ひじ"},
{ RightLowerArm,"右ひじ"},
{ LeftHand,"左手首"},
{ RightHand,"右手首"},
{"LeftToes","左つま先"},
{"RightToes","右つま先"},
{"LeftEye","左目"},
{"RightEye","右目"},
{"Jaw", null},
{ LeftThumbProximal, "左親指0"},
{ LeftThumbIntermediate,"左親指1"},
{ LeftThumbDistal,"左親指2"},
{ LeftIndexProximal,"左人指1"},
{"Left Index Intermediate","左人指2"},
{ LeftIndexDistal,"左人指3"},
{ LeftMiddleProximal,"左中指1"},
{"Left Middle Intermediate","左中指2"},
{ LeftMiddleDistal,"左中指3"},
{ LeftRingProximal,"左薬指1"},
{"Left Ring Intermediate","左薬指2"},
{ LeftRingDistal,"左薬指3"},
{ LeftLittleProximal,"左小指1"},
{"Left Little Intermediate","左小指2"},
{ LeftLittleDistal,"左小指3"},
{ RightThumbProximal, "右親指0"},
{ RightThumbIntermediate,"右親指1"},
{ RightThumbDistal,"右親指2"},
{ RightIndexProximal,"右人指1"},
{"Right Index Intermediate","右人指2"},
{ RightIndexDistal,"右人指3"},
{ RightMiddleProximal,"右中指1"},
{"Right Middle Intermediate","右中指2"},
{ RightMiddleDistal,"右中指3"},
{ RightRingProximal,"右薬指1"},
{"Right Ring Intermediate","右薬指2"},
{ RightRingDistal,"右薬指3"},
{ RightLittleProximal,"右小指1"},
{"Right Little Intermediate","右小指2"},
{ RightLittleDistal,"右小指3"},
{"UpperChest", "上半身2"}
};
public static Dictionary<string, string> Alt_OriginalNameDictionary = new Dictionary<string, string>()
{
{"右足先EX", "右つま先"},
{"左足先EX", "左つま先"},
{"右ひじ袖", "右ひじ"},
{"左ひじ袖", "左ひじ"}
};
public const string LeftShoulder = "LeftShoulder";
public const string RightShoulder = "RightShoulder";
public const string LeftUpperArm = "LeftUpperArm";
public const string RightUpperArm = "RightUpperArm";
public const string LeftLowerArm = "LeftLowerArm";
public const string RightLowerArm = "RightLowerArm";
public const string LeftHand = "LeftHand";
public const string RightHand = "RightHand";
public const string RightIndexProximal = "Right Index Proximal";
public const string RightIndexIntermediate = "Right Index Intermediate";
public const string RightIndexDistal = "Right Index Distal";
public const string LeftIndexProximal = "Left Index Proximal";
public const string LeftIndexIntermediate = "Left Index Intermediate";
public const string LeftIndexDistal = "Left Index Distal";
public const string RightMiddleProximal = "Right Middle Proximal";
public const string RightMiddleIntermediate = "Right Middle Intermediate";
public const string RightMiddleDistal = "Right Middle Distal";
public const string LeftMiddleProximal = "Left Middle Proximal";
public const string LeftMiddleIntermediate = "Left Middle Intermediate";
public const string LeftMiddleDistal = "Left Middle Distal";
public const string RightRingProximal = "Right Ring Proximal";
public const string RightRingIntermediate = "Right Ring Intermediate";
public const string RightRingDistal = "Right Ring Distal";
public const string LeftRingProximal = "Left Ring Proximal";
public const string LeftRingIntermediate = "Left Ring Intermediate";
public const string LeftRingDistal = "Left Ring Distal";
public const string RightLittleProximal = "Right Little Proximal";
public const string RightLittleIntermediate = "Right Little Intermediate";
public const string RightLittleDistal = "Right Little Distal";
public const string LeftLittleProximal = "Left Little Proximal";
public const string LeftLittleIntermediate = "Left Little Intermediate";
public const string LeftLittleDistal = "Left Little Distal";
public const string RightThumbProximal = "Right Thumb Proximal";
public const string RightThumbIntermediate = "Right Thumb Intermediate";
public const string RightThumbDistal = "Right Thumb Distal";
public const string LeftThumbProximal = "Left Thumb Proximal";
public const string LeftThumbIntermediate = "Left Thumb Intermediate";
public const string LeftThumbDistal = "Left Thumb Distal";
public const string BoneDAppend = "D";
public const string BoneSAppend = "S";
public const string BoneEXAppend = "EX";
//can be null
public Transform ModelRootTransform { get; private set; }
public string ModelPath { get; private set; } = "ModelPath";
public RawMMDModel RawMMDModel { get; private set; }
public SkinnedMeshRenderer SkinnedMeshRenderer { get; private set; } = new SkinnedMeshRenderer();
public Mesh Mesh { get; private set; }
public UnityEngine.Material[] Materials { get; private set; } = new UnityEngine.Material[] { };
public List<string> MaterialMorphNames { get; private set; } = new List<string>();
public Dictionary<Transform, int> OriginalBone_IndexDictionary { get; private set; }
= new Dictionary<Transform, int>();
public Dictionary<Transform, Transform> Alt_OriginalBoneDictionary { get; private set; }
= new Dictionary<Transform, Transform>();
private const string ColliderNameTail = "Collider";
private const float HalfPIDeg = Mathf.PI * Mathf.Rad2Deg / 2;
private const int MaxTextureSize = 1024;
private readonly ModelReadConfig modelReadConfig = new ModelReadConfig { GlobalToonPath = "" };
public static async Task<MMDModel> ImportModel(string filePath, bool autoShowModel = true)
{
GameObject modelObject = new GameObject();
MMDModel mmdModel = modelObject.AddComponent<MMDModel>();
await mmdModel.LoadModel(filePath);
if (autoShowModel) { mmdModel.ShowModel(); }
return mmdModel;
}
async Task<bool> LoadModel(string filePath)
{
ModelPath = filePath;
try
{
DirectoryInfo directoryInfo = new FileInfo(filePath).Directory;
if (directoryInfo == null)
{
throw new MMDFileParseException(filePath + " does not belong to any directory.");
}
RawMMDModel = ModelReader.LoadMmdModel(filePath, modelReadConfig);
transform.name = RawMMDModel.Name;
string relativePath = directoryInfo.FullName;
MaterialLoader materialLoader = new MaterialLoader(new TextureLoader(relativePath, MaxTextureSize));
int vertCount = RawMMDModel.Vertices.Length;
int triangleCount = RawMMDModel.TriangleIndexes.Length / 3;
int[] triangles = RawMMDModel.TriangleIndexes;
string meshName = Path.GetFileName(filePath);
Mesh mesh = new Mesh
{
name = meshName,
vertices = new Vector3[vertCount],
normals = new Vector3[vertCount]
};
mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32;
FillSubMesh(mesh, triangleCount, triangles);
float[] uv = ExtratUv(RawMMDModel.Vertices);
mesh.uv = Utils.MmdUvToUnityUv(uv);
mesh.vertices = RawMMDModel.Vertices.Select(x => x.Coordinate).ToArray();
mesh.normals = RawMMDModel.Vertices.Select(x => x.Normal).ToArray();
mesh.boneWeights = RawMMDModel.Vertices.Select(x => ConvertBoneWeight(x.SkinningOperator)).ToArray();
mesh.RecalculateBounds();
Mesh = mesh;
await AttachVertexMorph(mesh);
await SearchForMaterialMorph();
Utils.ClearAllTransformChild(transform);
(GameObject rootObj, Transform[] bones) = CreateBones(model: RawMMDModel, parentOfAll: gameObject);
SkinnedMeshRenderer = rootObj.AddComponent<SkinnedMeshRenderer>();
SkinnedMeshRenderer.enabled = false;
SkinnedMeshRenderer.quality = SkinQuality.Bone4;
SkinnedMeshRenderer.rootBone = rootObj.transform;
InitializeBoneDictionaries(bones);
Materials = LoadModelMaterials(materialLoader, new MMDUnityConfig(), RawMMDModel);
ReorderRender(Materials);
SkinnedMeshRenderer.sharedMesh = mesh;
BuildBindpose(Mesh, bones, SkinnedMeshRenderer);
SkinnedMeshRenderer.materials = Materials;
MaterialMorphRemover.HideMaterialMorphs(this);
AttachPhysicComponents(bones, this);
}
catch (Exception e)
{
UnityEngine.Debug.LogException(e);
return false;
}
return true;
}
private static float[] ExtratUv(Vertex[] verts)
{
var ret = new float[verts.Length * 2];
for (var i = 0; i < verts.Length; ++i)
{
ret[2 * i] = verts[i].UvCoordinate.x;
ret[2 * i + 1] = verts[i].UvCoordinate.y;
}
return ret;
}
public UnityEngine.Material[] LoadModelMaterials(MaterialLoader materialLoader, MMDUnityConfig config, RawMMDModel model)
{
var ret = new UnityEngine.Material[model.Parts.Length];
for (var i = 0; i < model.Parts.Length; i++)
{
ret[i] = materialLoader.LoadMaterial(model.Parts[i].Material, config);
ret[i].name = model.Parts[i].Material.Name;
}
return ret;
}
private void FillSubMesh(Mesh mesh, int triangleCount, int[] triangles)
{
mesh.subMeshCount = RawMMDModel.Parts.Length;
for (var i = 0; i < RawMMDModel.Parts.Length; i++)
{
var modelPart = RawMMDModel.Parts[i];
if ((modelPart.BaseShift + modelPart.TriangleIndexNum) / 3 > triangleCount)
{
UnityEngine.Debug.LogError("too many triangles in model part " + i);
continue;
}
mesh.SetTriangles(Utils.ArrayToList(triangles, modelPart.BaseShift, modelPart.TriangleIndexNum), i);
}
}
private void InitializeBoneDictionaries(Transform[] bones)
{
int boneCount = bones.Length;
for (int i = 0; i < boneCount; i++)
{
if (Unity_MMDBoneNameDictionary.Values.Contains(bones[i].name))
{
OriginalBone_IndexDictionary.Add(bones[i], i);
}
}
foreach (Transform bone in bones)
{
if (OriginalBone_IndexDictionary.ContainsKey(bone)) { continue; }
if (Alt_OriginalBoneDictionary.ContainsKey(bone)) { continue; }
foreach (Transform originalBone in OriginalBone_IndexDictionary.Keys)
{
if (bone.name.Equals(originalBone.name + BoneDAppend)
|| bone.name.Equals(originalBone.name + BoneSAppend)
|| bone.name.Equals(originalBone.name + BoneEXAppend))
{
Alt_OriginalBoneDictionary.Add(bone, originalBone);
}
}
}
}
private void AttachPhysicComponents(Transform[] boneTransforms, MMDModel model)
{
GameObject[] bones = boneTransforms.Select(x => x.gameObject).ToArray();
int bonesCount = bones.Length;
Transform parentOfAll = model.gameObject.transform;
Dictionary<int, List<Collider>> colliderGroups = new Dictionary<int, List<Collider>>();
int rigidbodiesCount = model.RawMMDModel.Rigidbodies.Length;
for (int i = 0; i < rigidbodiesCount; i++)
{
MMDRigidBody mmdRigidBody = model.RawMMDModel.Rigidbodies[i];
if (bonesCount <= mmdRigidBody.AssociatedBoneIndex) { continue; }
GameObject bone = bones[mmdRigidBody.AssociatedBoneIndex];
if (Alt_OriginalBoneDictionary.ContainsKey(bone.transform))
{
bone = Alt_OriginalBoneDictionary[bone.transform].gameObject;
}
if (mmdRigidBody.Type == MMDRigidBody.RigidBodyType.RigidTypePhysicsGhost
|| mmdRigidBody.Type == MMDRigidBody.RigidBodyType.RigidTypePhysicsStrict)
{
continue;
}
if (!colliderGroups.ContainsKey(mmdRigidBody.CollisionGroup))
{
colliderGroups.Add(mmdRigidBody.CollisionGroup, new List<Collider>());
}
GameObject colliderObject = new GameObject(mmdRigidBody.Name + ColliderNameTail);
colliderObject.transform.parent = bone.transform;
Vector3 bonePosition = bone.transform.position - parentOfAll.position;
colliderObject.transform.localPosition = mmdRigidBody.Position - bonePosition;
colliderObject.transform.localRotation = Quaternion.Euler(mmdRigidBody.Rotation);
switch (mmdRigidBody.Shape)
{
case MMDRigidBody.RigidBodyShape.RigidShapeBox:
BoxCollider boxCollider = colliderObject.AddComponent<BoxCollider>();
colliderGroups[mmdRigidBody.CollisionGroup].Add(boxCollider);
boxCollider.size = mmdRigidBody.Dimemsions;
break;
case MMDRigidBody.RigidBodyShape.RigidShapeCapsule:
CapsuleCollider capsuleCollider = colliderObject.AddComponent<CapsuleCollider>();
colliderGroups[mmdRigidBody.CollisionGroup].Add(capsuleCollider);
capsuleCollider.radius = mmdRigidBody.Dimemsions.x;
capsuleCollider.height = mmdRigidBody.Dimemsions.y;
break;
case MMDRigidBody.RigidBodyShape.RigidShapeSphere:
SphereCollider sphereCollider = colliderObject.AddComponent<SphereCollider>();
colliderGroups[mmdRigidBody.CollisionGroup].Add(sphereCollider);
sphereCollider.radius = mmdRigidBody.Dimemsions.x;
break;
}
if (bone.GetComponent<Rigidbody>() != null) { continue; }
Rigidbody rigidbody = bone.AddComponent<Rigidbody>();
rigidbody.useGravity = true;
rigidbody.mass = mmdRigidBody.Mass;
rigidbody.drag = mmdRigidBody.TranslateDamp;
rigidbody.angularDrag = mmdRigidBody.RotateDamp;
if (mmdRigidBody.Type == MMDRigidBody.RigidBodyType.RigidTypeKinematic)
{
rigidbody.isKinematic = true;
}
}
//以下ジョイント
int jointCount = model.RawMMDModel.Joints.Length;
for (int i = 0; i < jointCount; i++)
{
LibMMD.Model.Joint mmdJoint = model.RawMMDModel.Joints[i];
int jointFromBoneIndex = model.RawMMDModel.Rigidbodies[mmdJoint.AssociatedRigidBodyIndex[0]].AssociatedBoneIndex;
int jointToBoneIndex = model.RawMMDModel.Rigidbodies[mmdJoint.AssociatedRigidBodyIndex[1]].AssociatedBoneIndex;
if (bonesCount <= jointFromBoneIndex || bonesCount <= jointToBoneIndex) { continue; }
GameObject jointFromObj = bones[jointFromBoneIndex];
GameObject jointToObj = bones[jointToBoneIndex];
Rigidbody jointToRigidbody = jointToObj.GetComponent<Rigidbody>();
if (jointToRigidbody == null) { continue; }
Rigidbody jointFromRigidbody = jointFromObj.GetComponent<Rigidbody>();
if (jointFromRigidbody == null)
{
//この場合jointFromObjは基本的に体の一部などの始点
jointFromRigidbody = jointFromObj.AddComponent<Rigidbody>();
jointFromRigidbody.isKinematic = true;
}
//すでに向こう側から接続していたら接続しない
HingeJoint[] counterJoint = jointToObj.GetComponents<HingeJoint>();
if (counterJoint.Any(x => x != null && jointFromRigidbody != null && x.connectedBody == jointFromRigidbody)) { continue; }
//残念ながら情報を落とす
HingeJoint joint = jointFromObj.AddComponent<HingeJoint>();
joint.connectedBody = jointToRigidbody;
joint.axis = Quaternion.Euler(mmdJoint.Rotation) * jointFromObj.transform.right;
joint.limits = new JointLimits
{
max = HalfPIDeg,
min = -HalfPIDeg
};
joint.useLimits = true;
joint.spring = new JointSpring
{
spring = mmdJoint.SpringTranslate.magnitude
};
joint.useSpring = true;
}
foreach (List<Collider> colliderGroup in colliderGroups.Values)
{
int colliderCount = colliderGroup.Count;
for (int i = 0; i < colliderCount; i++)
{
for (int j = 0; j < i; j++)
{
Physics.IgnoreCollision(colliderGroup[i], colliderGroup[j]);
}
}
}
}
private async Task AttachVertexMorph(Mesh mesh)
{
List<Morph> vertexMorphs = new List<Morph>();
foreach (Morph morph in RawMMDModel.Morphs)
{
if (morph.Type == Morph.MorphType.MorphTypeVertex)
{
vertexMorphs.Add(morph);
}
}
Vector3[] modelVertexVectors = RawMMDModel.Vertices.Select(x => x.Coordinate).ToArray();
Vector3[] modelVertexNormals = RawMMDModel.Vertices.Select(x => x.Normal).ToArray();
List<(string name, Vector3[] offsets, Vector3[] normals)> blendShapes = new List<(string, Vector3[], Vector3[])>();
await Task.Run(() =>
{
int vertexCount = RawMMDModel.Vertices.Length;
int vertexMorphsCount = vertexMorphs.Count;
for (int i = 0; i < vertexMorphsCount; i++)
{
Vector3[] offsets = new Vector3[vertexCount];
for (int j = 0; j < vertexCount; j++)
{
offsets[j] = Vector3.zero;
}
Vector3[] normals = new Vector3[vertexCount];
for (int j = 0; j < vertexCount; j++)
{
normals[j] = Vector3.zero;
}
bool isEmpty = true;
int morphDataCount = vertexMorphs[i].MorphDatas.Length;
for (int j = 0; j < morphDataCount; j++)
{
Morph.VertexMorphData vertexMorphData = (vertexMorphs[i].MorphDatas[j] as Morph.VertexMorphData);
int vertexIndex = vertexMorphData.VertexIndex;
if (vertexIndex > vertexCount) { continue; }
offsets[vertexIndex] = vertexMorphData.Offset;
normals[vertexIndex] = RawMMDModel.Vertices[vertexIndex].Normal;
isEmpty = false;
}
if (!isEmpty)
{
blendShapes.Add((vertexMorphs[i].Name, offsets, normals));
}
}
});
blendShapes.ForEach(x => mesh.AddBlendShapeFrame(x.name, 100f, x.offsets, x.normals, null));
}
private async Task SearchForMaterialMorph()
{
await Task.Run(() =>
{
foreach (Morph morph in RawMMDModel.Morphs)
{
if (morph.Type == Morph.MorphType.MorphTypeMaterial)
{
MaterialMorphNames.Add(morph.Name);
}
}
});
}
private (GameObject rootObj, Transform[] bones) CreateBones(RawMMDModel model, GameObject parentOfAll)
{
if (model == null)
{
UnityEngine.Debug.Log("モデルがないため骨構造を作れません");
return (null, null);
}
int boneCount = model.Bones.Length;
Transform[] bones = new Transform[boneCount];
for (int i = 0; i < boneCount; i++)
{
bones[i] = new GameObject(RawMMDModel.Bones[i].Name).transform;
bones[i].transform.position = RawMMDModel.Bones[i].Position;
}
GameObject rootObj = BuildUpParentChildStructure(model, parentOfAll, bones);
return (rootObj, bones);
}
GameObject BuildUpParentChildStructure(RawMMDModel model, GameObject parentOfAll, Transform[] bones)
{
GameObject rootObj = new GameObject("Root");
ModelRootTransform = rootObj.transform;
ModelRootTransform.parent = parentOfAll.transform;
rootObj.transform.localPosition = Vector3.zero;
rootObj.transform.localRotation = Quaternion.identity;
rootObj.transform.localScale = Vector3.one;
int boneCount = model.Bones.Length;
for (int i = 0, iMax = boneCount; i < iMax; ++i)
{
var parentBoneIndex = model.Bones[i].ParentIndex;
bones[i].parent = parentBoneIndex < bones.Length && parentBoneIndex >= 0
? bones[parentBoneIndex].transform
: ModelRootTransform;
}
return rootObj;
}
private static BoneWeight ConvertBoneWeight(SkinningOperator op)
{
var ret = new BoneWeight();
switch (op.Type)
{
case SkinningOperator.SkinningType.SkinningBdef1:
var bdef1 = (SkinningOperator.Bdef1)op.Param;
ret.boneIndex0 = bdef1.BoneId;
ret.weight0 = 1.0f;
break;
case SkinningOperator.SkinningType.SkinningBdef2:
var bdef2 = (SkinningOperator.Bdef2)op.Param;
ret.boneIndex0 = bdef2.BoneId[0];
ret.boneIndex1 = bdef2.BoneId[1];
ret.weight0 = bdef2.BoneWeight;
ret.weight1 = 1 - bdef2.BoneWeight;
break;
case SkinningOperator.SkinningType.SkinningBdef4:
var bdef4 = (SkinningOperator.Bdef4)op.Param;
ret.boneIndex0 = bdef4.BoneId[0];
ret.boneIndex1 = bdef4.BoneId[1];
ret.boneIndex2 = bdef4.BoneId[2];
ret.boneIndex3 = bdef4.BoneId[3];
ret.weight0 = bdef4.BoneWeight[0];
ret.weight1 = bdef4.BoneWeight[1];
ret.weight2 = bdef4.BoneWeight[2];
ret.weight3 = bdef4.BoneWeight[3];
break;
case SkinningOperator.SkinningType.SkinningSdef:
var sdef = (SkinningOperator.Sdef)op.Param;
ret.boneIndex0 = sdef.BoneId[0];
ret.boneIndex1 = sdef.BoneId[1];
ret.weight0 = sdef.BoneWeight;
ret.weight1 = 1 - sdef.BoneWeight;
break;
default:
throw new ArgumentOutOfRangeException();
}
return ret;
}
private void BuildBindpose(Mesh mesh, Transform[] bones, SkinnedMeshRenderer meshRenderer)
{
Matrix4x4[] bindposes = bones.Select(x => x.worldToLocalMatrix).ToArray();
mesh.bindposes = bindposes;
meshRenderer.bones = bones;
}
private int GetRelBoneIndexFromNearbyRigidbody(int rigidbodyIndex)
{
var boneCount = RawMMDModel.Bones.Length;
var result = RawMMDModel.Rigidbodies[rigidbodyIndex].AssociatedBoneIndex;
if (result < boneCount)
{
return result;
}
var jointAList = RawMMDModel.Joints.Where(x => x.AssociatedRigidBodyIndex[1] == rigidbodyIndex)
.Where(x => x.AssociatedRigidBodyIndex[0] < boneCount)
.Select(x => x.AssociatedRigidBodyIndex[0]);
foreach (var jointA in jointAList)
{
result = GetRelBoneIndexFromNearbyRigidbody(jointA);
if (result < boneCount)
{
return result;
}
}
var jointBList = RawMMDModel.Joints.Where(x => x.AssociatedRigidBodyIndex[0] == rigidbodyIndex)
.Where(x => x.AssociatedRigidBodyIndex[1] < boneCount)
.Select(x => x.AssociatedRigidBodyIndex[1]);
foreach (var jointB in jointBList)
{
result = GetRelBoneIndexFromNearbyRigidbody(jointB);
if (result < boneCount)
{
return result;
}
}
result = int.MaxValue;
return result;
}
private void ReorderRender(UnityEngine.Material[] materials)
{
if (materials.Length == 0)
{
return;
}
var order = new UnityEngine.Material[materials.Length];
Array.Copy(materials, order, materials.Length);
order.OrderBy(mat => mat.renderQueue);
var lastQueue = int.MinValue;
foreach (var mat in order)
{
if (lastQueue >= mat.renderQueue)
{
mat.renderQueue = lastQueue++;
}
else
{
lastQueue = mat.renderQueue;
}
}
}
public void ShowModel()
{
if (SkinnedMeshRenderer == null) { return; }
SkinnedMeshRenderer.enabled = true;
}
public void HideModel()
{
if (SkinnedMeshRenderer == null) { return; }
SkinnedMeshRenderer.enabled = false;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3d691346906868a42b19a716a0ca2ee3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,33 @@
using System;
namespace LibMMD.Unity3D
{
public enum MMDConfigSwitch
{
AsConfig = 0,
ForceTrue = 1,
ForceFalse = 2
}
public class MMDUnityConfig
{
public MMDConfigSwitch EnableDrawSelfShadow;
public MMDConfigSwitch EnableCastShadow;
public MMDConfigSwitch EnableEdge;
public static bool DealSwitch(MMDConfigSwitch switchVal, bool configVal)
{
switch (switchVal)
{
case MMDConfigSwitch.AsConfig:
return configVal;
case MMDConfigSwitch.ForceTrue:
return true;
case MMDConfigSwitch.ForceFalse:
return false;
default:
throw new ArgumentOutOfRangeException("switchVal", switchVal, null);
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 43735cc6fa2ef754296beb18361c4b93
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,171 @@
// ------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Mono Runtime Version: 4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
// ------------------------------------------------------------------------------
using System;
using System.Text;
using LibMMD.Material;
using UnityEngine;
namespace LibMMD.Unity3D
{
public class MaterialLoader : IDisposable
{
private readonly TextureLoader _textureLoader;
public MaterialLoader(TextureLoader textureLoader) {
_textureLoader = textureLoader;
}
public UnityEngine.Material LoadMaterial(MMDMaterial mmdMaterial, MMDUnityConfig config) {
var mainTexture = _textureLoader.LoadTexture(mmdMaterial.Texture);
var isTransparent = mmdMaterial.DiffuseColor.a < 0.9999f || mmdMaterial.EdgeColor.a < 0.9999f ||
IsTextireTransparent(mainTexture);
var material = new UnityEngine.Material (GetShader (mmdMaterial, config, isTransparent));
ConfigMaterial(mmdMaterial, config, material, mainTexture);
return material;
}
public void RefreshMaterialConfig(MMDMaterial mmdMaterial,MMDUnityConfig config, UnityEngine.Material material)
{
var mainTexture = _textureLoader.LoadTexture(mmdMaterial.Texture);
var isTransparent = mmdMaterial.DiffuseColor.a < 0.9999f || mmdMaterial.EdgeColor.a < 0.9999f ||
IsTextireTransparent(mainTexture);
var shaderName = BuildShaderName(mmdMaterial, config, isTransparent);
if (!material.shader.name.Equals(shaderName))
{
material.shader = Shader.Find(shaderName);
}
ConfigMaterial(mmdMaterial, config, material,mainTexture);
}
private void ConfigMaterial(MMDMaterial mmdMaterial, MMDUnityConfig config, UnityEngine.Material material, Texture mainTexture)
{
material.SetColor("_Color", mmdMaterial.DiffuseColor);
material.SetFloat("_Opacity", mmdMaterial.DiffuseColor.a);
material.SetColor("_AmbColor", mmdMaterial.AmbientColor);
material.SetColor("_SpecularColor", mmdMaterial.SpecularColor);
material.SetFloat("_Shininess", mmdMaterial.Shiness);
material.SetFloat("_OutlineWidth", mmdMaterial.EdgeSize);
material.SetColor("_OutlineColor", mmdMaterial.EdgeColor);
if (mainTexture != null)
{
material.mainTexture = mainTexture;
material.mainTextureScale = new Vector2(1, 1);
}
if (mmdMaterial.SubTextureType != MMDMaterial.SubTextureTypeEnum.MatSubTexOff)
{
var additionalTexture =
mmdMaterial.SubTexture == null ? null : _textureLoader.LoadTexture(mmdMaterial.SubTexture);
if (additionalTexture != null)
{
additionalTexture.wrapMode = TextureWrapMode.Clamp;
switch (mmdMaterial.SubTextureType)
{
case MMDMaterial.SubTextureTypeEnum.MatSubTexSpa:
material.SetTexture("_SphereAddTex", additionalTexture);
material.SetTextureScale("_SphereAddTex", new Vector2(1, 1));
break;
case MMDMaterial.SubTextureTypeEnum.MatSubTexSph:
material.SetTexture("_SphereMulTex", additionalTexture);
material.SetTextureScale("_SphereMulTex", new Vector2(1, 1));
break;
}
}
}
RefreshShaderKeywords(mmdMaterial, config, material);
var toonTexture = _textureLoader.LoadTexture(mmdMaterial.Toon);
if (toonTexture != null)
{
toonTexture.wrapMode = TextureWrapMode.Clamp;
material.SetTexture("_ToonTex", toonTexture);
material.SetTextureScale("_ToonTex", new Vector2(1, 1));
}
}
private void RefreshShaderKeywords(MMDMaterial mmdMaterial, MMDUnityConfig config, UnityEngine.Material material)
{
RefreshDrawSelfShadowKeyword(MMDUnityConfig.DealSwitch(config.EnableDrawSelfShadow, mmdMaterial.DrawSelfShadow),
material);
}
private void RefreshDrawSelfShadowKeyword(bool drawSelfshadow, UnityEngine.Material material)
{
if (drawSelfshadow)
{
material.EnableKeyword("SELFSHADOW_ON");
material.DisableKeyword("SELFSHADOW_OFF");
}
else
{
material.DisableKeyword("SELFSHADOW_ON");
material.EnableKeyword("SELFSHADOW_OFF");
}
}
public void Dispose ()
{
if (_textureLoader != null) {
_textureLoader.Dispose ();
}
}
private static Shader GetShader(MMDMaterial mmdMaterial, MMDUnityConfig config, bool isTransparent)
{
//"MMD/Transparent/PMDMaterial-with-Outline-CullBack-NoCastShadow"
var shaderName = BuildShaderName(mmdMaterial, config, isTransparent);
var ret = Shader.Find (shaderName);
if (ret == null) {
Debug.LogWarning("Can't find shader "+ shaderName);
}
return ret;
}
private static string BuildShaderName(MMDMaterial mmdMaterial, MMDUnityConfig config, bool isTransparent)
{
var shaderNameBuilder = new StringBuilder();
shaderNameBuilder.Append("VRM/");
if (isTransparent)
{
shaderNameBuilder.Append("UnlitTransparentZWrite");
}
else
{
shaderNameBuilder.Append("UnlitTexture");
}
var shaderName = shaderNameBuilder.ToString();
return shaderName;
}
private static bool IsTextireTransparent(Texture texture) {
try {
var tex2D = texture as Texture2D;
if (tex2D == null) {
return false;
}
var pixels = tex2D.GetPixels ();
foreach (var color in pixels) {
if (color.a < 0.99f) {
return true;
}
}
} catch {
}
return false;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c96bc2c33987dc744a12399c9e4af3ce
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,20 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace LibMMD.Unity3D
{
public class MaterialMorphRemover
{
public static void HideMaterialMorphs(MMDModel mmdModel)
{
foreach (UnityEngine.Material material in mmdModel.SkinnedMeshRenderer.sharedMaterials)
{
if (mmdModel.MaterialMorphNames.Contains(material.name))
{
material.shader = Shader.Find("Custom/VoidShader");
}
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1a4d8655d04c12a45be046f9d8cd31de
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,43 @@
// ------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Mono Runtime Version: 4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
// ------------------------------------------------------------------------------
using UnityEngine;
namespace LibMMD.Unity3D
{
public class ModelPart
{
public enum SubTextureTypeEnum {
MatSubTexOff,
MatSubTexSph,
MatSubTexSpa,
MatSubTexSub
};
public string ToonPath { get; set;}
public string TexturePath { get; set;}
public string SubTexturePath { get; set;}
public int TriangleNum { get; set;}
public int BaseShift { get; set;}
public Color DiffuseColor { get; set;}
public Color SpecularColor { get; set;}
public Color AmbientColor { get; set;}
public float Shininess { get; set;}
public bool DrawDoubleFace { get; set;}
public bool DrawGroundShadow { get; set;}
public bool CastSelfShadow { get; set;}
public bool DastSelfShadow { get; set;}
public bool DrawSelfShadow { get; set;}
public bool DrawEdge { get; set;}
public Color EdgeColor { get; set;}
public float EdgeSize { get; set;}
public SubTextureTypeEnum SubTextureType { get; set;}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 29488fac476a8cf44ae86fb0c0ccb5e9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,89 @@
using LibMMD.Unity3D;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using UnityEngine;
public class PMXModelLoader
{
public async static Task<Transform> LoadPMXModel(string path, RuntimeAnimatorController runtimeAnimatorController, Transform parent, bool autoShowModel = true)
{
if (!File.Exists(path))
{
UnityEngine.Debug.Log(path);
UnityEngine.Debug.Log("与えられたパスにファイルが存在ません");
return null;
}
MMDModel mmdModel = null;
try
{
mmdModel = await MMDModel.ImportModel(path, autoShowModel);
}
catch(Exception ex)
{
UnityEngine.Debug.Log(ex.Message);
return null;
}
if (mmdModel == null) { return null; }
try
{
AvatarMaker avaterMaker = mmdModel.gameObject.AddComponent<AvatarMaker>();
avaterMaker.Prepare(mmdModel, runtimeAnimatorController);
await avaterMaker.MakeAvatar();
#if UNITY_EDITOR
GameObject.DestroyImmediate(avaterMaker);
#else
GameObject.Destroy(avaterMaker);
#endif
}
catch (Exception ex)
{
UnityEngine.Debug.Log("アバターの作成に失敗しました");
UnityEngine.Debug.Log(path);
AvatarMaker avaterMaker = mmdModel.gameObject.GetComponent<AvatarMaker>();
#if UNITY_EDITOR
if (avaterMaker != null)
{
GameObject.DestroyImmediate(avaterMaker);
}
#else
if (avaterMaker != null)
{
GameObject.Destroy(avaterMaker);
}
#endif
return mmdModel.transform;
}
mmdModel.transform.parent = parent;
mmdModel.transform.localPosition = Vector3.zero;
mmdModel.transform.localRotation = Quaternion.identity;
return mmdModel.transform;
}
public async static Task<Transform> LoadPMXModel(string path, RuntimeAnimatorController runtimeAnimatorController, bool autoShowModel = true)
{
return await LoadPMXModel(path, runtimeAnimatorController, null, autoShowModel);
}
public async static Task<Transform> LoadPMXModel(string path, RuntimeAnimatorController runtimeAnimatorController)
{
return await LoadPMXModel(path, runtimeAnimatorController, null);
}
public async static Task<Transform> LoadPMXModel(string path, bool autoShowModel = true)
{
return await LoadPMXModel(path, null, null, autoShowModel);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 39b14547e60be694ea7d26990aa49e91
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,299 @@
using System;
using System.Collections.Generic;
using System.IO;
using LibMMD.Material;
using LibMMD.Unity3D.ImageLoader;
using UnityEngine;
using Object = UnityEngine.Object;
namespace LibMMD.Unity3D
{
public class TextureLoader : IDisposable
{
private const string SysToonPath = "LibMmd/SysToon/";
private readonly string _relativePath;
private readonly int _maxTextureSize;
private static readonly HashSet<string> SysToonNames = new HashSet<string>();
private readonly Dictionary<string, Texture> _textureMap = new Dictionary<string, Texture>();
static TextureLoader()
{
SysToonNames.Add("toon0.bmp");
for (var i = 1; i < 9; i++)
{
SysToonNames.Add("toon0" + i + ".bmp");
}
SysToonNames.Add("toon10.bmp");
}
public TextureLoader(string relativePath, int maxTextureSize = 0)
{
_relativePath = relativePath + Path.DirectorySeparatorChar;
_maxTextureSize = maxTextureSize;
}
public Texture LoadTexture(MMDTexture mmdTexture)
{
return mmdTexture == null ? null : LoadTexture(mmdTexture.TexturePath);
}
private Texture LoadTexture(string path)
{
if (string.IsNullOrEmpty(path))
{
return null;
}
path = ReplaceFileSeperator(path);
Texture ret;
if (_textureMap.TryGetValue(path, out ret))
{
return ret;
}
ret = DoLoadTexture(path);
if (ret != null)
{
_textureMap.Add(path, ret);
}
return ret;
}
public void Dispose()
{
foreach (var entry in _textureMap)
{
if (SysToonNames.Contains(entry.Key))
{
continue;
}
var tex2D = entry.Value as Texture2D;
if (tex2D == null)
{
continue;
}
Object.Destroy(tex2D);
}
}
private string ReplaceFileSeperator(string path)
{
if (Path.DirectorySeparatorChar.Equals('/'))
{
path = path.Replace('\\', '/');
}
else if (Path.DirectorySeparatorChar.Equals('\\'))
{
path = path.Replace('/', '\\');
}
return path;
}
private Texture DoLoadTexture(string path)
{
if (SysToonNames.Contains(path))
{
var filename = Path.GetFileNameWithoutExtension(path);
return Resources.Load(SysToonPath + filename) as Texture;
}
if (!File.Exists(path))
{
path = _relativePath + path;
}
if (!File.Exists(path))
{
Debug.LogFormat("texture file not exists {0}", path);
return null;
}
try
{
var extension = Path.GetExtension(path);
if (extension != null)
{
var ext = extension.ToLower();
Texture ret;
if (".jpg".Equals(ext) || ".jpeg".Equals(ext))
{
ret = LoadJpg(path);
}
else if (".png".Equals(ext))
{
ret = LoadPng(path);
}
else if (".bmp".Equals(ext))
{
ret = LoadBmp(path);
}
else if (".tga".Equals(ext))
{
ret = LoadTga(path);
}
else if (".dds".Equals(ext))
{
ret = LoadDds(path);
}
else
{
ret = TryLoadWithAllFormats(path);
}
var tex2D = ret as Texture2D;
if (tex2D != null)
{
RescaleLargeTexture(tex2D);
//tex2D.Compress(false);
ret.name = Path.GetFileName(path);
}
return ret;
}
}
catch (Exception e)
{
Debug.LogWarningFormat("failed to load texture {0}, {1}", path, e);
}
return null;
}
private void RescaleLargeTexture(Texture2D tex)
{
if (_maxTextureSize <= 0)
{
return;
}
if (tex.width <= _maxTextureSize && tex.height <= _maxTextureSize)
{
return;
}
try
{
TextureScale.Bilinear(tex, Math.Min(tex.width, _maxTextureSize), Math.Min(tex.height, _maxTextureSize));
}
catch (Exception e)
{
Debug.LogWarningFormat("Resize texture failed. {0}", e);
}
}
private Texture DoLoadCubemap(string path)
{
var tex2D = DoLoadTexture(path) as Texture2D;
return tex2D == null ? null : Texture2DToCubeMap(tex2D);
}
private static Cubemap Texture2DToCubeMap(Texture2D texture2D)
{
if (texture2D.width != texture2D.height)
{
Debug.LogWarning("Can't convert a Texture2D to Cubemap when width and height are different");
return null;
}
var ret = new Cubemap(texture2D.width, texture2D.format, false);
var texPixels = texture2D.GetPixels();
ret.SetPixels(texPixels, CubemapFace.NegativeX);
ret.SetPixels(texPixels, CubemapFace.NegativeY);
ret.SetPixels(texPixels, CubemapFace.NegativeZ);
ret.SetPixels(texPixels, CubemapFace.PositiveX);
ret.SetPixels(texPixels, CubemapFace.PositiveY);
ret.SetPixels(texPixels, CubemapFace.PositiveZ);
ret.Apply();
return ret;
}
private static Texture TryLoadWithAllFormats(string path)
{
var ret = LoadBmp(path);
if (ret != null)
{
return ret;
}
ret = LoadPng(path);
if (ret != null)
{
return ret;
}
ret = LoadJpg(path);
return ret;
}
private static Texture LoadJpg(string path)
{
return LoadWithUnity(path);
}
private static Texture LoadPng(string path)
{
return LoadWithUnity(path);
}
private static Texture LoadBmp(string path)
{
var img = BitmapLoader.LoadFromFile(path);
if (img == null)
{
return null;
}
var ret = new Texture2D(img.Width, img.Height, TextureFormat.ARGB32, false);
ret.SetPixels(img.Pixels);
ret.Apply();
return ret;
}
private static Texture LoadTga(string path)
{
return TargaImage.LoadTargaImage(path);
}
private static Texture LoadDds(string path)
{
var bytes = File.ReadAllBytes(path);
var width = DdsLoader.DdsGetWidth(bytes);
var height = DdsLoader.DdsGetHeight(bytes);
var nMipmap = DdsLoader.DdsGetMipmap(bytes);
var hasMipmap = nMipmap > 1;
var ret = new Texture2D(width, height, TextureFormat.ARGB32, hasMipmap);
if (hasMipmap)
{
for (var i = 0; i < nMipmap; i++)
{
var intColors = DdsLoader.DdsRead(bytes, DdsLoader.DdsReaderArgb, i);
ret.SetPixels(IntsArgbToColorUpsideDown(intColors, width / (1 << i), height / (1 << i)), i);
}
}
else
{
var intColors = DdsLoader.DdsRead(bytes, DdsLoader.DdsReaderArgb, 0);
ret.SetPixels(IntsArgbToColorUpsideDown(intColors, width, height));
}
ret.Apply();
return ret;
}
public static Color[] IntsArgbToColorUpsideDown(int[] ints, int width, int height)
{
var ret = new Color[ints.Length];
for (var i = 0; i < height; i++)
{
for (var j = 0; j < width; j++)
{
var intColor = ints[i * width + j];
var dstIndex = (height - 1 - i) * width + j;
ret[dstIndex].b = (intColor & 0xFF) / 255.0f;
ret[dstIndex].g = ((intColor >> 8) & 0xFF) / 255.0f;
ret[dstIndex].r = ((intColor >> 16) & 0xFF) / 255.0f;
ret[dstIndex].a = ((intColor >> 24) & 0xFF) / 255.0f;
}
}
return ret;
}
private static Texture LoadWithUnity(string path)
{
if (!File.Exists(path)) return null;
var fileData = File.ReadAllBytes(path);
var tex = new Texture2D(2, 2);
tex.LoadImage(fileData);
return tex;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1f3af3954c1f52a4f9be720b11a77a5c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,153 @@
// Only works on ARGB32, RGB24 and Alpha8 textures that are marked readable
using System.Threading;
using UnityEngine;
using Object = System.Object;
namespace LibMMD.Unity3D
{
public class TextureScale
{
public class ThreadData
{
public int Start;
public int End;
public ThreadData (int s, int e) {
Start = s;
End = e;
}
}
private static Color[] _texColors;
private static Color[] _newColors;
private static int _w;
private static float _ratioX;
private static float _ratioY;
private static int _w2;
private static int _finishCount;
private static Mutex _mutex;
public static void Point (Texture2D tex, int newWidth, int newHeight)
{
ThreadedScale (tex, newWidth, newHeight, false);
}
public static void Bilinear (Texture2D tex, int newWidth, int newHeight)
{
ThreadedScale (tex, newWidth, newHeight, true);
}
private static void ThreadedScale (Texture2D tex, int newWidth, int newHeight, bool useBilinear)
{
_texColors = tex.GetPixels();
_newColors = new Color[newWidth * newHeight];
if (useBilinear)
{
_ratioX = 1.0f / ((float)newWidth / (tex.width-1));
_ratioY = 1.0f / ((float)newHeight / (tex.height-1));
}
else {
_ratioX = ((float)tex.width) / newWidth;
_ratioY = ((float)tex.height) / newHeight;
}
_w = tex.width;
_w2 = newWidth;
var cores = Mathf.Min(SystemInfo.processorCount, newHeight);
var slice = newHeight/cores;
_finishCount = 0;
if (_mutex == null) {
_mutex = new Mutex(false);
}
if (cores > 1)
{
int i;
ThreadData threadData;
for (i = 0; i < cores-1; i++) {
threadData = new ThreadData(slice * i, slice * (i + 1));
var ts = useBilinear ? new ParameterizedThreadStart(BilinearScale) : new ParameterizedThreadStart(PointScale);
var thread = new Thread(ts);
thread.Start(threadData);
}
threadData = new ThreadData(slice*i, newHeight);
if (useBilinear)
{
BilinearScale(threadData);
}
else
{
PointScale(threadData);
}
while (_finishCount < cores)
{
Thread.Sleep(1);
}
}
else
{
ThreadData threadData = new ThreadData(0, newHeight);
if (useBilinear)
{
BilinearScale(threadData);
}
else
{
PointScale(threadData);
}
}
tex.Resize(newWidth, newHeight);
tex.SetPixels(_newColors);
tex.Apply();
}
public static void BilinearScale (Object obj)
{
var threadData = (ThreadData) obj;
for (var y = threadData.Start; y < threadData.End; y++)
{
var yFloor = (int)Mathf.Floor(y * _ratioY);
var y1 = yFloor * _w;
var y2 = (yFloor+1) * _w;
var yw = y * _w2;
for (var x = 0; x < _w2; x++) {
var xFloor = (int)Mathf.Floor(x * _ratioX);
var xLerp = x * _ratioX-xFloor;
_newColors[yw + x] = ColorLerpUnclamped(ColorLerpUnclamped(_texColors[y1 + xFloor], _texColors[y1 + xFloor+1], xLerp),
ColorLerpUnclamped(_texColors[y2 + xFloor], _texColors[y2 + xFloor+1], xLerp),
y*_ratioY-yFloor);
}
}
_mutex.WaitOne();
_finishCount++;
_mutex.ReleaseMutex();
}
public static void PointScale (object obj)
{
var threadData = (ThreadData) obj;
for (var y = threadData.Start; y < threadData.End; y++)
{
var thisY = (int)(_ratioY * y) * _w;
var yw = y * _w2;
for (var x = 0; x < _w2; x++) {
_newColors[yw + x] = _texColors[(int)(thisY + _ratioX*x)];
}
}
_mutex.WaitOne();
_finishCount++;
_mutex.ReleaseMutex();
}
private static Color ColorLerpUnclamped (Color c1, Color c2, float value)
{
return new Color (c1.r + (c2.r - c1.r)*value,
c1.g + (c2.g - c1.g)*value,
c1.b + (c2.b - c1.b)*value,
c1.a + (c2.a - c1.a)*value);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c343dd8f2f3826b46aae4a5a03d11559
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,107 @@
// ------------------------------------------------------------------------------
// <autogenerated>
// This code was generated by a tool.
// Mono Runtime Version: 4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </autogenerated>
// ------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using UnityEngine;
using Object = UnityEngine.Object;
namespace LibMMD.Unity3D
{
public class Utils
{
public static void UpdateFloatsToVector3(float[] f, Vector3[] dst) {
var size = f.Length / 3;
for (var i=0; i<size; i++) {
var baseIndex = i * 3;
dst[i].x = f[baseIndex];
dst[i].y = f[baseIndex + 1];
dst[i].z = f[baseIndex + 2];
}
}
public static void MmdUvToUnityUv(float[] f, Vector2[] dst) {
var size = f.Length / 2;
for (var i=0; i<size; i++) {
var baseIndex = i * 2;
dst [i].x = f [baseIndex];
dst [i].y = 1.0f - f [baseIndex + 1];
}
}
public static Vector2[] MmdUvToUnityUv(float[] f)
{
var size = f.Length / 2;
Vector2[] dst = new Vector2[size];
for (var i = 0; i < size; i++)
{
var baseIndex = i * 2;
dst[i].x = f[baseIndex];
dst[i].y = 1.0f - f[baseIndex + 1];
}
return dst;
}
public static List<T> ArrayToList<T>(T[] src, int srcIndex, int length) {
var ret = new List<T> (length);
var endPos = srcIndex + length;
for (var i=srcIndex; i<endPos; i++) {
ret.Add(src[i]);
}
return ret;
}
public static Color FloatRgbaToColor(float[] rgba) {
return new Color (rgba [0], rgba [1], rgba [2], rgba [3]);
}
public static Color[] Bgra32ToColors(byte[] bytes) {
var pixelCount = bytes.Length / 4;
var ret = new Color[pixelCount];
for (var i = 0; i < pixelCount; i++) {
var offset = i * 4;
ret [i] = new Color (
bytes [offset + 2] / 255.0f,
bytes [offset + 1] / 255.0f,
bytes [offset + 0] / 255.0f,
bytes [offset + 3] / 255.0f
);
}
return ret;
}
public static void ClearAllTransformChild(Transform t) {
var itemCount = t.childCount;
for (var i = 0; i < itemCount; i++) {
Object.Destroy (t.GetChild(i).gameObject);
}
}
public static void DisposeIgnoreException(IDisposable disposable)
{
if (disposable == null)
{
return;
}
try
{
disposable.Dispose();
}
catch(Exception e)
{
Debug.LogException(e);
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4c73962d47ee810458530b5825717184
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: