From 33943e42059238d27f1741c4bc5baf65b29393eb Mon Sep 17 00:00:00 2001 From: CroakFang <1605296300@qq.com> Date: Fri, 30 Jun 2023 14:08:40 +0800 Subject: [PATCH] import pmx plugin --- ... Jobs (Unity 2018.2.4f1).unitypackage.meta | 7 + .../IK Jobs (Unity 2019.3).unitypackage.meta | 7 + ...culus Integration v1.37).unitypackage.meta | 7 + ...4.28f1, PlayMaker 1.9.0).unitypackage.meta | 7 + ..., SteamVR Plugin v2.2.0).unitypackage.meta | 7 + ... 2017.4.28f1, UMA 2.8.1).unitypackage.meta | 7 + .../Scripts/{Exporter.meta => Exporters.meta} | 0 .../{Exporter => Exporters}/ModelExporter.cs | 0 .../ModelExporter.cs.meta | 0 .../TextureExporter.cs | 0 .../TextureExporter.cs.meta | 0 .../Exporters/UnityPMXRuntimeLoader.meta | 8 + .../UnityPMXRuntimeLoader}/LICENSE | 0 .../UnityPMXRuntimeLoader/LICENSE.meta | 7 + .../UnityPMXRuntimeLoader/LibMMD.meta | 8 + .../LibMMD/Extension.meta | 8 + .../LibMMD/Extension/Texture2DExtension.cs | 26 + .../Extension/Texture2DExtension.cs.meta | 11 + .../LibMMD/Material.meta | 8 + .../LibMMD/Material/MMDMaterial.cs | 41 + .../LibMMD/Material/MMDMaterial.cs.meta | 11 + .../LibMMD/Material/MMDTexture.cs | 35 + .../LibMMD/Material/MMDTexture.cs.meta | 11 + .../UnityPMXRuntimeLoader/LibMMD/Model.meta | 8 + .../LibMMD/Model/Bone.cs | 160 ++ .../LibMMD/Model/Bone.cs.meta | 11 + .../LibMMD/Model/Joint.cs | 24 + .../LibMMD/Model/Joint.cs.meta | 11 + .../LibMMD/Model/MMDRigidBody.cs | 38 + .../LibMMD/Model/MMDRigidBody.cs.meta | 11 + .../LibMMD/Model/Morph.cs | 87 + .../LibMMD/Model/Morph.cs.meta | 11 + .../LibMMD/Model/Part.cs | 9 + .../LibMMD/Model/Part.cs.meta | 11 + .../LibMMD/Model/RawMMDModel.cs | 83 + .../LibMMD/Model/RawMMDModel.cs.meta | 11 + .../LibMMD/Model/SkinningOperator.cs | 64 + .../LibMMD/Model/SkinningOperator.cs.meta | 11 + .../LibMMD/Model/Vertex.cs | 14 + .../LibMMD/Model/Vertex.cs.meta | 11 + .../UnityPMXRuntimeLoader/LibMMD/Reader.meta | 8 + .../LibMMD/Reader/ByteArrayReader.cs | 32 + .../LibMMD/Reader/ByteArrayReader.cs.meta | 11 + .../LibMMD/Reader/MMDFileParseException.cs | 11 + .../Reader/MMDFileParseException.cs.meta | 11 + .../LibMMD/Reader/ModelReadConfig.cs | 7 + .../LibMMD/Reader/ModelReadConfig.cs.meta | 11 + .../LibMMD/Reader/ModelReader.cs | 39 + .../LibMMD/Reader/ModelReader.cs.meta | 11 + .../LibMMD/Reader/PMDReader.cs | 730 ++++++ .../LibMMD/Reader/PMDReader.cs.meta | 11 + .../LibMMD/Reader/PMXReader.cs | 627 +++++ .../LibMMD/Reader/PMXReader.cs.meta | 11 + .../LibMMD/Resources.meta | 8 + .../LibMMD/Resources/LibMmd.meta | 8 + .../LibMMD/Resources/LibMmd/SysToon.meta | 8 + .../LibMMD/Resources/LibMmd/SysToon/toon0.bmp | Bin 0 -> 3126 bytes .../Resources/LibMmd/SysToon/toon0.bmp.meta | 112 + .../Resources/LibMmd/SysToon/toon01.bmp | Bin 0 -> 3128 bytes .../Resources/LibMmd/SysToon/toon01.bmp.meta | 112 + .../Resources/LibMmd/SysToon/toon02.bmp | Bin 0 -> 3128 bytes .../Resources/LibMmd/SysToon/toon02.bmp.meta | 112 + .../Resources/LibMmd/SysToon/toon03.bmp | Bin 0 -> 3128 bytes .../Resources/LibMmd/SysToon/toon03.bmp.meta | 112 + .../Resources/LibMmd/SysToon/toon04.bmp | Bin 0 -> 3128 bytes .../Resources/LibMmd/SysToon/toon04.bmp.meta | 112 + .../Resources/LibMmd/SysToon/toon05.bmp | Bin 0 -> 3126 bytes .../Resources/LibMmd/SysToon/toon05.bmp.meta | 112 + .../Resources/LibMmd/SysToon/toon06.bmp | Bin 0 -> 3126 bytes .../Resources/LibMmd/SysToon/toon06.bmp.meta | 112 + .../Resources/LibMmd/SysToon/toon07.bmp | Bin 0 -> 3126 bytes .../Resources/LibMmd/SysToon/toon07.bmp.meta | 112 + .../Resources/LibMmd/SysToon/toon08.bmp | Bin 0 -> 3126 bytes .../Resources/LibMmd/SysToon/toon08.bmp.meta | 112 + .../Resources/LibMmd/SysToon/toon09.bmp | Bin 0 -> 3126 bytes .../Resources/LibMmd/SysToon/toon09.bmp.meta | 112 + .../Resources/LibMmd/SysToon/toon10.bmp | Bin 0 -> 3126 bytes .../Resources/LibMmd/SysToon/toon10.bmp.meta | 112 + .../LibMMD/Resources/Prefabs.meta | 8 + .../Resources/Prefabs/MMDGameObject.prefab | 145 ++ .../Prefabs/MMDGameObject.prefab.meta | 7 + .../LibMMD/Resources/Shaders.meta | 8 + ...shPmdMaterial-CullBack-NoCastShadow.shader | 56 + ...Material-CullBack-NoCastShadow.shader.meta | 9 + .../Shaders/MeshPmdMaterial-CullBack.shader | 70 + .../MeshPmdMaterial-CullBack.shader.meta | 9 + .../MeshPmdMaterial-NoCastShadow.shader | 56 + .../MeshPmdMaterial-NoCastShadow.shader.meta | 9 + ...aterial-Trans-CullBack-NoCastShadow.shader | 57 + ...al-Trans-CullBack-NoCastShadow.shader.meta | 9 + .../MeshPmdMaterial-Trans-CullBack.shader | 77 + ...MeshPmdMaterial-Trans-CullBack.shader.meta | 9 + .../MeshPmdMaterial-Trans-NoCastShadow.shader | 67 + ...PmdMaterial-Trans-NoCastShadow.shader.meta | 9 + .../Shaders/MeshPmdMaterial-Trans.shader | 87 + .../Shaders/MeshPmdMaterial-Trans.shader.meta | 9 + .../Resources/Shaders/MeshPmdMaterial.shader | 70 + .../Shaders/MeshPmdMaterial.shader.meta | 9 + .../Shaders/MeshPmdMaterialDummy.shader | 55 + .../Shaders/MeshPmdMaterialDummy.shader.meta | 9 + ...terialOutline-CullBack-NoCastShadow.shader | 67 + ...lOutline-CullBack-NoCastShadow.shader.meta | 9 + .../MeshPmdMaterialOutline-CullBack.shader | 81 + ...eshPmdMaterialOutline-CullBack.shader.meta | 9 + ...MeshPmdMaterialOutline-NoCastShadow.shader | 67 + ...mdMaterialOutline-NoCastShadow.shader.meta | 9 + ...Outline-Trans-CullBack-NoCastShadow.shader | 72 + ...ne-Trans-CullBack-NoCastShadow.shader.meta | 9 + ...shPmdMaterialOutline-Trans-CullBack.shader | 92 + ...MaterialOutline-Trans-CullBack.shader.meta | 9 + ...dMaterialOutline-Trans-NoCastShadow.shader | 82 + ...rialOutline-Trans-NoCastShadow.shader.meta | 9 + .../MeshPmdMaterialOutline-Trans.shader | 101 + .../MeshPmdMaterialOutline-Trans.shader.meta | 9 + .../Shaders/MeshPmdMaterialOutline.shader | 80 + .../MeshPmdMaterialOutline.shader.meta | 9 + .../MeshPmdMaterialShadowVertFrag.cginc | 42 + .../MeshPmdMaterialShadowVertFrag.cginc.meta | 9 + .../Shaders/MeshPmdMaterialSurface.cginc | 91 + .../Shaders/MeshPmdMaterialSurface.cginc.meta | 9 + .../Shaders/MeshPmdMaterialVertFrag.cginc | 45 + .../MeshPmdMaterialVertFrag.cginc.meta | 9 + .../UnityPMXRuntimeLoader/LibMMD/Unity3D.meta | 8 + .../LibMMD/Unity3D/AvatarMaker.cs | 277 ++ .../LibMMD/Unity3D/AvatarMaker.cs.meta | 11 + .../LibMMD/Unity3D/ImageLoader.meta | 8 + .../Unity3D/ImageLoader/BitmapLoader.cs | 197 ++ .../Unity3D/ImageLoader/BitmapLoader.cs.meta | 11 + .../LibMMD/Unity3D/ImageLoader/DDSLoader.cs | 743 ++++++ .../Unity3D/ImageLoader/DDSLoader.cs.meta | 11 + .../LibMMD/Unity3D/ImageLoader/TargaImage.cs | 2273 +++++++++++++++++ .../Unity3D/ImageLoader/TargaImage.cs.meta | 11 + .../Unity3D/ImageLoader/TextureImage.cs | 37 + .../Unity3D/ImageLoader/TextureImage.cs.meta | 11 + .../LibMMD/Unity3D/MMDModel.cs | 626 +++++ .../LibMMD/Unity3D/MMDModel.cs.meta | 11 + .../LibMMD/Unity3D/MMDUnityConfig.cs | 33 + .../LibMMD/Unity3D/MMDUnityConfig.cs.meta | 11 + .../LibMMD/Unity3D/MaterialLoader.cs | 171 ++ .../LibMMD/Unity3D/MaterialLoader.cs.meta | 11 + .../LibMMD/Unity3D/MaterialMorphRemover.cs | 20 + .../Unity3D/MaterialMorphRemover.cs.meta | 11 + .../LibMMD/Unity3D/ModelPart.cs | 43 + .../LibMMD/Unity3D/ModelPart.cs.meta | 11 + .../LibMMD/Unity3D/PMXModelLoader.cs | 89 + .../LibMMD/Unity3D/PMXModelLoader.cs.meta | 11 + .../LibMMD/Unity3D/TextureLoader.cs | 299 +++ .../LibMMD/Unity3D/TextureLoader.cs.meta | 11 + .../LibMMD/Unity3D/TextureScale.cs | 153 ++ .../LibMMD/Unity3D/TextureScale.cs.meta | 11 + .../LibMMD/Unity3D/Utils.cs | 107 + .../LibMMD/Unity3D/Utils.cs.meta | 11 + .../UnityPMXRuntimeLoader/LibMMD/Util.meta | 8 + .../LibMMD/Util/BlockingQueue.cs | 96 + .../LibMMD/Util/BlockingQueue.cs.meta | 11 + .../LibMMD/Util/LogUtil.cs | 27 + .../LibMMD/Util/LogUtil.cs.meta | 11 + .../LibMMD/Util/MMDReaderUtil.cs | 125 + .../LibMMD/Util/MMDReaderUtil.cs.meta | 11 + .../LibMMD/Util/MMDTextureUtil.cs | 31 + .../LibMMD/Util/MMDTextureUtil.cs.meta | 11 + .../LibMMD/Util/MathUtil.cs | 277 ++ .../LibMMD/Util/MathUtil.cs.meta | 11 + .../LibMMD/Util/MatrixExtensions.cs | 40 + .../LibMMD/Util/MatrixExtensions.cs.meta | 11 + .../LibMMD/Util/SynchronizedQueue.cs | 33 + .../LibMMD/Util/SynchronizedQueue.cs.meta | 11 + .../LibMMD/Util/Tools.cs | 10 + .../LibMMD/Util/Tools.cs.meta | 11 + .../LibMMD/Util/TransformExtensions.cs | 14 + .../LibMMD/Util/TransformExtensions.cs.meta | 11 + .../LibMMD/libmmd-for-unity LICENSE.txt | 29 + .../LibMMD/libmmd-for-unity LICENSE.txt.meta | 7 + .../Exporters/UnityPMXRuntimeLoader/README.md | 12 + .../UnityPMXRuntimeLoader/README.md.meta | 7 + .../Exporters/UnityPMXRuntimeLoader/VRM.meta | 8 + .../VRM/UniVRM LICENSE.txt | 23 + .../VRM/UniVRM LICENSE.txt.meta | 7 + .../UnityPMXRuntimeLoader/VRM/UniVRM.meta | 8 + .../VRM/UniVRM/Resources.meta | 8 + .../VRM/UniVRM/Resources/Shaders.meta | 8 + .../Shaders/VRMShaders.shadervariants | 33 + .../Shaders/VRMShaders.shadervariants.meta | 9 + .../Resources/Shaders/VRMUnlitCutout.shader | 61 + .../Shaders/VRMUnlitCutout.shader.meta | 9 + .../Resources/Shaders/VRMUnlitTexture.shader | 58 + .../Shaders/VRMUnlitTexture.shader.meta | 9 + .../Shaders/VRMUnlitTransparent.shader | 61 + .../Shaders/VRMUnlitTransparent.shader.meta | 9 + .../Shaders/VRMUnlitTransparentZWrite.shader | 61 + .../VRMUnlitTransparentZWrite.shader.meta | 9 + .../UnityPMXRuntimeLoader/VoidShader.meta | 8 + .../VoidShader/CustomVoidShader.shader | 8 + .../VoidShader/CustomVoidShader.shader.meta | 9 + .../Scripts/{ => Exporters}/VMDRecorder.meta | 0 Assets/Scripts/Exporters/VMDRecorder/LICENSE | 21 + .../{ => Exporters}/VMDRecorder/LICENSE.meta | 0 .../VMDRecorder/UnityCameraVMDRecorder.cs | 0 .../UnityCameraVMDRecorder.cs.meta | 0 .../VMDRecorder/UnityHumanoidVMDRecorder.cs | 0 .../UnityHumanoidVMDRecorder.cs.meta | 0 .../UnityVMDQuaternionExtentions.cs | 0 .../UnityVMDQuaternionExtentions.cs.meta | 0 203 files changed, 11810 insertions(+) create mode 100644 Assets/Plugins/RootMotion/FinalIK/_Integration/IK Jobs (Unity 2018.2.4f1).unitypackage.meta create mode 100644 Assets/Plugins/RootMotion/FinalIK/_Integration/IK Jobs (Unity 2019.3).unitypackage.meta create mode 100644 Assets/Plugins/RootMotion/FinalIK/_Integration/Oculus (Unity 2017.4.28f1, Oculus Integration v1.37).unitypackage.meta create mode 100644 Assets/Plugins/RootMotion/FinalIK/_Integration/Playmaker (Unity 2017.4.28f1, PlayMaker 1.9.0).unitypackage.meta create mode 100644 Assets/Plugins/RootMotion/FinalIK/_Integration/Steam VR (Unity 2017.4.28f1, SteamVR Plugin v2.2.0).unitypackage.meta create mode 100644 Assets/Plugins/RootMotion/FinalIK/_Integration/UMA (Unity 2017.4.28f1, UMA 2.8.1).unitypackage.meta rename Assets/Scripts/{Exporter.meta => Exporters.meta} (100%) rename Assets/Scripts/{Exporter => Exporters}/ModelExporter.cs (100%) rename Assets/Scripts/{Exporter => Exporters}/ModelExporter.cs.meta (100%) rename Assets/Scripts/{Exporter => Exporters}/TextureExporter.cs (100%) rename Assets/Scripts/{Exporter => Exporters}/TextureExporter.cs.meta (100%) create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader.meta rename Assets/Scripts/{VMDRecorder => Exporters/UnityPMXRuntimeLoader}/LICENSE (100%) create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LICENSE.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Extension.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Extension/Texture2DExtension.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Extension/Texture2DExtension.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material/MMDMaterial.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material/MMDMaterial.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material/MMDTexture.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material/MMDTexture.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Bone.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Bone.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Joint.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Joint.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/MMDRigidBody.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/MMDRigidBody.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Morph.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Morph.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Part.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Part.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/RawMMDModel.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/RawMMDModel.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/SkinningOperator.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/SkinningOperator.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Vertex.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Vertex.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ByteArrayReader.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ByteArrayReader.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/MMDFileParseException.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/MMDFileParseException.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ModelReadConfig.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ModelReadConfig.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ModelReader.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ModelReader.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/PMDReader.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/PMDReader.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/PMXReader.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/PMXReader.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon0.bmp create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon0.bmp.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon01.bmp create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon01.bmp.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon02.bmp create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon02.bmp.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon03.bmp create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon03.bmp.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon04.bmp create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon04.bmp.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon05.bmp create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon05.bmp.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon06.bmp create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon06.bmp.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon07.bmp create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon07.bmp.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon08.bmp create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon08.bmp.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon09.bmp create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon09.bmp.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon10.bmp create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon10.bmp.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Prefabs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Prefabs/MMDGameObject.prefab create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Prefabs/MMDGameObject.prefab.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterial-CullBack-NoCastShadow.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterial-CullBack-NoCastShadow.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterial-CullBack.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterial-CullBack.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterial-NoCastShadow.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterial-NoCastShadow.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterial-Trans-CullBack-NoCastShadow.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterial-Trans-CullBack-NoCastShadow.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterial-Trans-CullBack.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterial-Trans-CullBack.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterial-Trans-NoCastShadow.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterial-Trans-NoCastShadow.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterial-Trans.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterial-Trans.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterial.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterial.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialDummy.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialDummy.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialOutline-CullBack-NoCastShadow.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialOutline-CullBack-NoCastShadow.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialOutline-CullBack.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialOutline-CullBack.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialOutline-NoCastShadow.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialOutline-NoCastShadow.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialOutline-Trans-CullBack-NoCastShadow.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialOutline-Trans-CullBack-NoCastShadow.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialOutline-Trans-CullBack.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialOutline-Trans-CullBack.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialOutline-Trans-NoCastShadow.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialOutline-Trans-NoCastShadow.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialOutline-Trans.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialOutline-Trans.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialOutline.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialOutline.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialShadowVertFrag.cginc create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialShadowVertFrag.cginc.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialSurface.cginc create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialSurface.cginc.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialVertFrag.cginc create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/Shaders/MeshPmdMaterialVertFrag.cginc.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/AvatarMaker.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/AvatarMaker.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/BitmapLoader.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/BitmapLoader.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/DDSLoader.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/DDSLoader.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/TargaImage.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/TargaImage.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/TextureImage.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/TextureImage.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MMDModel.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MMDModel.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MMDUnityConfig.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MMDUnityConfig.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MaterialLoader.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MaterialLoader.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MaterialMorphRemover.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MaterialMorphRemover.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ModelPart.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ModelPart.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/PMXModelLoader.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/PMXModelLoader.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/TextureLoader.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/TextureLoader.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/TextureScale.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/TextureScale.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/Utils.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/Utils.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/BlockingQueue.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/BlockingQueue.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/LogUtil.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/LogUtil.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MMDReaderUtil.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MMDReaderUtil.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MMDTextureUtil.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MMDTextureUtil.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MathUtil.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MathUtil.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MatrixExtensions.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MatrixExtensions.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/SynchronizedQueue.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/SynchronizedQueue.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/Tools.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/Tools.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/TransformExtensions.cs create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/TransformExtensions.cs.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/libmmd-for-unity LICENSE.txt create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/libmmd-for-unity LICENSE.txt.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/README.md create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/README.md.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM LICENSE.txt create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM LICENSE.txt.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMShaders.shadervariants create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMShaders.shadervariants.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitCutout.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitCutout.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTexture.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTexture.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTransparent.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTransparent.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTransparentZWrite.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTransparentZWrite.shader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VoidShader.meta create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VoidShader/CustomVoidShader.shader create mode 100644 Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VoidShader/CustomVoidShader.shader.meta rename Assets/Scripts/{ => Exporters}/VMDRecorder.meta (100%) create mode 100644 Assets/Scripts/Exporters/VMDRecorder/LICENSE rename Assets/Scripts/{ => Exporters}/VMDRecorder/LICENSE.meta (100%) rename Assets/Scripts/{ => Exporters}/VMDRecorder/UnityCameraVMDRecorder.cs (100%) rename Assets/Scripts/{ => Exporters}/VMDRecorder/UnityCameraVMDRecorder.cs.meta (100%) rename Assets/Scripts/{ => Exporters}/VMDRecorder/UnityHumanoidVMDRecorder.cs (100%) rename Assets/Scripts/{ => Exporters}/VMDRecorder/UnityHumanoidVMDRecorder.cs.meta (100%) rename Assets/Scripts/{ => Exporters}/VMDRecorder/UnityVMDQuaternionExtentions.cs (100%) rename Assets/Scripts/{ => Exporters}/VMDRecorder/UnityVMDQuaternionExtentions.cs.meta (100%) diff --git a/Assets/Plugins/RootMotion/FinalIK/_Integration/IK Jobs (Unity 2018.2.4f1).unitypackage.meta b/Assets/Plugins/RootMotion/FinalIK/_Integration/IK Jobs (Unity 2018.2.4f1).unitypackage.meta new file mode 100644 index 0000000..fd115b1 --- /dev/null +++ b/Assets/Plugins/RootMotion/FinalIK/_Integration/IK Jobs (Unity 2018.2.4f1).unitypackage.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: b3e58808cb15120468eafdef64280407 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/RootMotion/FinalIK/_Integration/IK Jobs (Unity 2019.3).unitypackage.meta b/Assets/Plugins/RootMotion/FinalIK/_Integration/IK Jobs (Unity 2019.3).unitypackage.meta new file mode 100644 index 0000000..00a91fc --- /dev/null +++ b/Assets/Plugins/RootMotion/FinalIK/_Integration/IK Jobs (Unity 2019.3).unitypackage.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 59d63bcae2fecff42be7b4fc8b1df10f +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/RootMotion/FinalIK/_Integration/Oculus (Unity 2017.4.28f1, Oculus Integration v1.37).unitypackage.meta b/Assets/Plugins/RootMotion/FinalIK/_Integration/Oculus (Unity 2017.4.28f1, Oculus Integration v1.37).unitypackage.meta new file mode 100644 index 0000000..d9fcdc9 --- /dev/null +++ b/Assets/Plugins/RootMotion/FinalIK/_Integration/Oculus (Unity 2017.4.28f1, Oculus Integration v1.37).unitypackage.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 7d1083877b3838042b9e91b249731b89 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/RootMotion/FinalIK/_Integration/Playmaker (Unity 2017.4.28f1, PlayMaker 1.9.0).unitypackage.meta b/Assets/Plugins/RootMotion/FinalIK/_Integration/Playmaker (Unity 2017.4.28f1, PlayMaker 1.9.0).unitypackage.meta new file mode 100644 index 0000000..7ce27d6 --- /dev/null +++ b/Assets/Plugins/RootMotion/FinalIK/_Integration/Playmaker (Unity 2017.4.28f1, PlayMaker 1.9.0).unitypackage.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 0512c18ad5403428db876010796c1cda +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/RootMotion/FinalIK/_Integration/Steam VR (Unity 2017.4.28f1, SteamVR Plugin v2.2.0).unitypackage.meta b/Assets/Plugins/RootMotion/FinalIK/_Integration/Steam VR (Unity 2017.4.28f1, SteamVR Plugin v2.2.0).unitypackage.meta new file mode 100644 index 0000000..839abdf --- /dev/null +++ b/Assets/Plugins/RootMotion/FinalIK/_Integration/Steam VR (Unity 2017.4.28f1, SteamVR Plugin v2.2.0).unitypackage.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 57ddc43ace113674392034825a54600a +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/RootMotion/FinalIK/_Integration/UMA (Unity 2017.4.28f1, UMA 2.8.1).unitypackage.meta b/Assets/Plugins/RootMotion/FinalIK/_Integration/UMA (Unity 2017.4.28f1, UMA 2.8.1).unitypackage.meta new file mode 100644 index 0000000..21cc026 --- /dev/null +++ b/Assets/Plugins/RootMotion/FinalIK/_Integration/UMA (Unity 2017.4.28f1, UMA 2.8.1).unitypackage.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: d00cc5f8e672c264d856aa10ed20df7e +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporter.meta b/Assets/Scripts/Exporters.meta similarity index 100% rename from Assets/Scripts/Exporter.meta rename to Assets/Scripts/Exporters.meta diff --git a/Assets/Scripts/Exporter/ModelExporter.cs b/Assets/Scripts/Exporters/ModelExporter.cs similarity index 100% rename from Assets/Scripts/Exporter/ModelExporter.cs rename to Assets/Scripts/Exporters/ModelExporter.cs diff --git a/Assets/Scripts/Exporter/ModelExporter.cs.meta b/Assets/Scripts/Exporters/ModelExporter.cs.meta similarity index 100% rename from Assets/Scripts/Exporter/ModelExporter.cs.meta rename to Assets/Scripts/Exporters/ModelExporter.cs.meta diff --git a/Assets/Scripts/Exporter/TextureExporter.cs b/Assets/Scripts/Exporters/TextureExporter.cs similarity index 100% rename from Assets/Scripts/Exporter/TextureExporter.cs rename to Assets/Scripts/Exporters/TextureExporter.cs diff --git a/Assets/Scripts/Exporter/TextureExporter.cs.meta b/Assets/Scripts/Exporters/TextureExporter.cs.meta similarity index 100% rename from Assets/Scripts/Exporter/TextureExporter.cs.meta rename to Assets/Scripts/Exporters/TextureExporter.cs.meta diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader.meta new file mode 100644 index 0000000..7e507e7 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4764e6b71c398c84c89691fc908d8dd9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/VMDRecorder/LICENSE b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LICENSE similarity index 100% rename from Assets/Scripts/VMDRecorder/LICENSE rename to Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LICENSE diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LICENSE.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LICENSE.meta new file mode 100644 index 0000000..3840d69 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LICENSE.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 35aeaadcbad6b854a802ff3599f97f74 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD.meta new file mode 100644 index 0000000..5472d62 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: aa28e550e06110d46a2730835d37116e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Extension.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Extension.meta new file mode 100644 index 0000000..1d12bf5 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Extension.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: eda5c0d55dec76c489bd59a4e8998ada +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Extension/Texture2DExtension.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Extension/Texture2DExtension.cs new file mode 100644 index 0000000..a5cb59a --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Extension/Texture2DExtension.cs @@ -0,0 +1,26 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +public static class Texture2DExtension +{ + public static Texture2D CreateReadabeTexture2D(this Texture2D texture2d) + { + RenderTexture renderTexture = RenderTexture.GetTemporary( + texture2d.width, + texture2d.height, + 0, + RenderTextureFormat.Default, + RenderTextureReadWrite.Linear); + + Graphics.Blit(texture2d, renderTexture); + RenderTexture previous = RenderTexture.active; + RenderTexture.active = renderTexture; + Texture2D readableTextur2D = new Texture2D(texture2d.width, texture2d.height); + readableTextur2D.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0); + readableTextur2D.Apply(); + RenderTexture.active = previous; + RenderTexture.ReleaseTemporary(renderTexture); + return readableTextur2D; + } +} diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Extension/Texture2DExtension.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Extension/Texture2DExtension.cs.meta new file mode 100644 index 0000000..aa40512 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Extension/Texture2DExtension.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3b8cc2a385b1d5c4fb754bc89a35af77 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material.meta new file mode 100644 index 0000000..aeb2ce2 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 99947f5bd2591ae4085f2494567a6621 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material/MMDMaterial.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material/MMDMaterial.cs new file mode 100644 index 0000000..60e3ef9 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material/MMDMaterial.cs @@ -0,0 +1,41 @@ +using UnityEngine; + +namespace LibMMD.Material +{ + public class MMDMaterial + { + public enum SubTextureTypeEnum : byte + { + MatSubTexOff = 0, + MatSubTexSph = 1, + MatSubTexSpa = 2, + MatSubTexSub = 3 + } + + public string Name { get; set; } + public string NameEn { get; set; } + + public Color DiffuseColor { get; set; } + public Color SpecularColor { get; set; } + public Color AmbientColor { get; set; } + + public float Shiness { get; set; } + + public bool DrawDoubleFace { get; set; } + public bool DrawGroundShadow { get; set; } + public bool CastSelfShadow { get; set; } + public bool DrawSelfShadow { get; set; } + public bool DrawEdge { get; set; } + + public Color EdgeColor { get; set; } + public float EdgeSize { get; set; } + + public MMDTexture Toon { get; set; } + public MMDTexture Texture { get; set; } + public MMDTexture SubTexture { get; set; } + public SubTextureTypeEnum SubTextureType { get; set; } + + + public string MetaInfo { get; set; } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material/MMDMaterial.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material/MMDMaterial.cs.meta new file mode 100644 index 0000000..8507f33 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material/MMDMaterial.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 439296348e1847745b21029b3e124fb3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material/MMDTexture.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material/MMDTexture.cs new file mode 100644 index 0000000..b78ffa9 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material/MMDTexture.cs @@ -0,0 +1,35 @@ +namespace LibMMD.Material +{ + public class MMDTexture + { + public string TexturePath { get; set; } + + public MMDTexture(string texturePath) + { + TexturePath = texturePath; + } + + protected bool Equals(MMDTexture other) + { + return string.Equals(TexturePath, other.TexturePath); + } + + public override bool Equals(object obj) + { + if (ReferenceEquals(null, obj)) return false; + if (ReferenceEquals(this, obj)) return true; + if (obj.GetType() != this.GetType()) return false; + return Equals((MMDTexture) obj); + } + + public override int GetHashCode() + { + return TexturePath != null ? TexturePath.GetHashCode() : 0; + } + + private MMDTexture() + { + + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material/MMDTexture.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material/MMDTexture.cs.meta new file mode 100644 index 0000000..823ed7f --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Material/MMDTexture.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 748fb3d767b3fb84faabacb9d3899280 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model.meta new file mode 100644 index 0000000..74fb852 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e8dd6dee04f840d43985c9bddcdbf3e1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Bone.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Bone.cs new file mode 100644 index 0000000..5fc91ad --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Bone.cs @@ -0,0 +1,160 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace LibMMD.Model +{ + public class Bone + { + public class IkLink + { + public int LinkIndex { get; set; } + public bool HasLimit { get; set; } + public Vector3 LoLimit { get; set; } + public Vector3 HiLimit { get; set; } + + public static IkLink CopyOf(IkLink ikLink) + { + return new IkLink + { + LinkIndex = ikLink.LinkIndex, + HasLimit = ikLink.HasLimit, + LoLimit = ikLink.LoLimit, + HiLimit = ikLink.HiLimit + }; + } + } + + public class ChildBone + { + public bool ChildUseId { get; set; } + public Vector3 Offset { get; set; } + public int Index { get; set; } + + public static ChildBone CopyOf(ChildBone childBone) + { + return new ChildBone + { + ChildUseId = childBone.ChildUseId, + Offset = childBone.Offset, + Index = childBone.Index + }; + } + } + + + public class AppendBone + { + public int Index { get; set; } + public float Ratio { get; set; } + + public static AppendBone CopyOf(AppendBone appendBone) + { + return new AppendBone + { + Index = appendBone.Index, + Ratio = appendBone.Ratio + }; + } + } + + public class IkInfo + { + public int IkTargetIndex { get; set; } + public int CcdIterateLimit { get; set; } + public float CcdAngleLimit { get; set; } + public IkLink[] IkLinks { get; set; } + + public static IkInfo CopyOf(IkInfo ikInfo) + { + var ikLinksCopy = new IkLink[ikInfo.IkLinks.Length]; + ikInfo.IkLinks.CopyTo(ikLinksCopy, 0); + return new IkInfo + { + IkTargetIndex = ikInfo.IkTargetIndex, + CcdIterateLimit = ikInfo.CcdIterateLimit, + CcdAngleLimit = ikInfo.CcdAngleLimit, + IkLinks = ikLinksCopy + }; + } + } + + public class LocalAxis + { + public Vector3 AxisX { get; set; } + public Vector3 AxisY { get; set; } + public Vector3 AxisZ { get; set; } + + public static LocalAxis CopyOf(LocalAxis localAxis) + { + return new LocalAxis + { + AxisX = localAxis.AxisX, + AxisY = localAxis.AxisY, + AxisZ = localAxis.AxisZ + }; + } + } + + public Bone() + { + ChildBoneVal = new ChildBone(); + AppendBoneVal = new AppendBone(); + LocalAxisVal = new LocalAxis(); + } + + public string Name { get; set; } + public string NameEn { get; set; } + public Vector3 Position { get; set; } + public int ParentIndex { get; set; } + public int TransformLevel { get; set; } + public bool Rotatable { get; set; } + public bool Movable { get; set; } + public bool Visible { get; set; } + public bool Controllable { get; set; } + public bool HasIk { get; set; } + public bool AppendRotate { get; set; } + public bool AppendTranslate { get; set; } + public bool RotAxisFixed { get; set; } + public bool UseLocalAxis { get; set; } + public bool PostPhysics { get; set; } + public bool ReceiveTransform { get; set; } + public ChildBone ChildBoneVal { get; set; } + public AppendBone AppendBoneVal { get; set; } + public Vector3 RotAxis { get; set; } + public LocalAxis LocalAxisVal { get; set; } + public int ExportKey { get; set; } + public IkInfo IkInfoVal { get; set; } + + public static Bone CopyOf(Bone bone) + { + return new Bone + { + Name = bone.Name, + NameEn = bone.NameEn, + Position = bone.Position, + ParentIndex = bone.ParentIndex, + TransformLevel = bone.TransformLevel, + Rotatable = bone.Rotatable, + Movable = bone.Movable, + Visible = bone.Visible, + Controllable = bone.Controllable, + HasIk = bone.HasIk, + AppendRotate = bone.AppendRotate, + AppendTranslate = bone.AppendTranslate, + RotAxisFixed = bone.RotAxisFixed, + UseLocalAxis = bone.UseLocalAxis, + PostPhysics = bone.PostPhysics, + ReceiveTransform = bone.ReceiveTransform, + ChildBoneVal = ChildBone.CopyOf(bone.ChildBoneVal), + AppendBoneVal = AppendBone.CopyOf(bone.AppendBoneVal), + RotAxis = bone.RotAxis, + LocalAxisVal = LocalAxis.CopyOf(bone.LocalAxisVal), + ExportKey = bone.ExportKey, + IkInfoVal = IkInfo.CopyOf(bone.IkInfoVal), + }; + } + + + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Bone.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Bone.cs.meta new file mode 100644 index 0000000..7b7aadc --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Bone.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0cd3fbcfbcc9edc4a8ba7660a838d4dc +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Joint.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Joint.cs new file mode 100644 index 0000000..78a8569 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Joint.cs @@ -0,0 +1,24 @@ +using UnityEngine; + +namespace LibMMD.Model +{ + public class Joint + { + public Joint() + { + AssociatedRigidBodyIndex = new int[2]; + } + + public string Name { get; set; } + public string NameEn { get; set; } + public int[] AssociatedRigidBodyIndex { get; set; } + public Vector3 Position { get; set; } + public Vector3 Rotation { get; set; } + public Vector3 PositionLowLimit { get; set; } + public Vector3 PositionHiLimit { get; set; } + public Vector3 RotationLowLimit { get; set; } + public Vector3 RotationHiLimit { get; set; } + public Vector3 SpringTranslate { get; set; } + public Vector3 SpringRotate { get; set; } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Joint.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Joint.cs.meta new file mode 100644 index 0000000..a85c157 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Joint.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 10f6db9a9b776f341bfd7b5aabda88ae +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/MMDRigidBody.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/MMDRigidBody.cs new file mode 100644 index 0000000..acdd713 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/MMDRigidBody.cs @@ -0,0 +1,38 @@ +using UnityEngine; + +namespace LibMMD.Model +{ + public class MMDRigidBody + { + public enum RigidBodyShape : byte + { + RigidShapeSphere = 0x00, + RigidShapeBox = 0x01, + RigidShapeCapsule = 0x02 + } + + public enum RigidBodyType : byte + { + RigidTypeKinematic = 0x00, + RigidTypePhysics = 0x01, + RigidTypePhysicsStrict = 0x02, + RigidTypePhysicsGhost = 0x03 + } + + public string Name { get; set; } + public string NameEn { get; set; } + public int AssociatedBoneIndex { get; set; } + public int CollisionGroup { get; set; } + public ushort CollisionMask { get; set; } + public RigidBodyShape Shape { get; set; } + public Vector3 Dimemsions { get; set; } + public Vector3 Position { get; set; } + public Vector3 Rotation { get; set; } + public float Mass { get; set; } + public float TranslateDamp { get; set; } + public float RotateDamp { get; set; } + public float Restitution { get; set; } + public float Friction { get; set; } + public RigidBodyType Type { get; set; } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/MMDRigidBody.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/MMDRigidBody.cs.meta new file mode 100644 index 0000000..e6f6062 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/MMDRigidBody.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 395400370dc114b4bbe68e03a1c99a0c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Morph.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Morph.cs new file mode 100644 index 0000000..f980cc9 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Morph.cs @@ -0,0 +1,87 @@ +using System.Collections.Generic; +using LibMMD.Util; +using UnityEngine; + +namespace LibMMD.Model +{ + public class Morph + { + public enum MorphCategory : byte + { + MorphCatSystem = 0x00, + MorphCatEyebrow = 0x01, + MorphCatEye = 0x02, + MorphCatMouth = 0x03, + MorphCatOther = 0x04 + } + + public enum MorphType : byte + { + MorphTypeGroup = 0x00, + MorphTypeVertex = 0x01, + MorphTypeBone = 0x02, + MorphTypeUv = 0x03, + MorphTypeExtUv1 = 0x04, + MorphTypeExtUv2 = 0x05, + MorphTypeExtUv3 = 0x06, + MorphTypeExtUv4 = 0x07, + MorphTypeMaterial = 0x08 + } + + public abstract class MorphData + { + } + + public class GroupMorphData : MorphData + { + public int MorphIndex { get; set; } + public float MorphRate { get; set; } + } + + public class VertexMorphData : MorphData + { + public int VertexIndex { get; set; } + public Vector3 Offset { get; set; } + } + + public class BoneMorphData : MorphData + { + public int BoneIndex { get; set; } + public Vector3 Translation { get; set; } + public Quaternion Rotation { get; set; } + } + + public class UvMorphData : MorphData + { + public int VertexIndex { get; set; } + public Vector4 Offset { get; set; } + } + + public class MaterialMorphData : MorphData + { + public enum MaterialMorphMethod : byte { + MorphMatMul = 0x00, + MorphMatAdd = 0x01 + } + + public int MaterialIndex { get; set; } + public bool Global { get; set; } + public MaterialMorphMethod Method { get; set; } + public Color Diffuse { get; set; } + public Color Specular { get; set; } + public Color Ambient { get; set; } + public float Shiness { get; set; } + public Color EdgeColor { get; set; } + public float EdgeSize { get; set; } + public Vector4 Texture { get; set; } + public Vector4 SubTexture { get; set; } + public Vector4 ToonTexture { get; set; } + } + + public string Name { get; set; } + public string NameEn { get; set; } + public MorphCategory Category { get; set; } + public MorphType Type { get; set; } + public MorphData[] MorphDatas { get; set; } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Morph.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Morph.cs.meta new file mode 100644 index 0000000..4da7bbd --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Morph.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f7f998f4d72211a4bbfa615fed8ceacb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Part.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Part.cs new file mode 100644 index 0000000..828e9d3 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Part.cs @@ -0,0 +1,9 @@ +namespace LibMMD.Model +{ + public class Part + { + public Material.MMDMaterial Material { get; set; } + public int BaseShift { get; set; } //注意这个和libmmd里的含义不同,这里是三角形顶点数 + public int TriangleIndexNum { get; set; } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Part.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Part.cs.meta new file mode 100644 index 0000000..3f1659a --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Part.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d0fb693cf5950c84499b613bb97a23eb +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/RawMMDModel.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/RawMMDModel.cs new file mode 100644 index 0000000..3837f42 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/RawMMDModel.cs @@ -0,0 +1,83 @@ +using System; + +namespace LibMMD.Model +{ + public class RawMMDModel + { + public string Name { get; set; } + public string NameEn { get; set; } + public string Description { get; set; } + public string DescriptionEn { get; set; } + public Vertex[] Vertices { get; set; } + public int ExtraUvNumber { get; set; } + public int[] TriangleIndexes { get; set; } + public Part[] Parts { get; set; } + public Bone[] Bones { get; set; } + public Morph[] Morphs { get; set; } + public MMDRigidBody[] Rigidbodies { get; set; } + public Joint[] Joints { get; set; } + + public void Normalize() + { + foreach (var vertex in Vertices) + { + switch (vertex.SkinningOperator.Type) + { + case SkinningOperator.SkinningType.SkinningBdef2: + { + var oldBdef2 = (SkinningOperator.Bdef2) vertex.SkinningOperator.Param; + var weight = oldBdef2.BoneWeight; + if (Math.Abs(weight) < 0.000001f) + { + var bdef1 = new SkinningOperator.Bdef1 {BoneId = oldBdef2.BoneId[1]}; + vertex.SkinningOperator.Param = bdef1; + vertex.SkinningOperator.Type = SkinningOperator.SkinningType.SkinningBdef1; + } + else if (Math.Abs(weight - 1.0f) < 0.00001f) + { + var bdef1 = new SkinningOperator.Bdef1 {BoneId = oldBdef2.BoneId[0]}; + vertex.SkinningOperator.Param = bdef1; + vertex.SkinningOperator.Type = SkinningOperator.SkinningType.SkinningBdef1; + } + break; + } + case SkinningOperator.SkinningType.SkinningSdef: + { + var oldSdef = (SkinningOperator.Sdef) vertex.SkinningOperator.Param; + var bone0 = oldSdef.BoneId[0]; + var bone1 = oldSdef.BoneId[1]; + var weight = oldSdef.BoneWeight; + if ( + Bones[bone0].ParentIndex != bone1 && + Bones[bone1].ParentIndex != bone0 + ) + { + if (Math.Abs(weight) < 0.000001f) + { + var bdef1 = new SkinningOperator.Bdef1 {BoneId = bone1}; + vertex.SkinningOperator.Param = bdef1; + vertex.SkinningOperator.Type = SkinningOperator.SkinningType.SkinningBdef1; + } + else if (Math.Abs(weight - 1.0f) < 0.00001f) + { + var bdef1 = new SkinningOperator.Bdef1 {BoneId = bone0}; + vertex.SkinningOperator.Param = bdef1; + vertex.SkinningOperator.Type = SkinningOperator.SkinningType.SkinningBdef1; + } + else + { + var bdef2 = new SkinningOperator.Bdef2(); + bdef2.BoneId[0] = bone0; + bdef2.BoneId[1] = bone1; + bdef2.BoneWeight = weight; + vertex.SkinningOperator.Param = bdef2; + vertex.SkinningOperator.Type = SkinningOperator.SkinningType.SkinningBdef2; + } + } + break; + } + } + } + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/RawMMDModel.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/RawMMDModel.cs.meta new file mode 100644 index 0000000..dc6429a --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/RawMMDModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 05367ea617bee1747a4786e33ec02123 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/SkinningOperator.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/SkinningOperator.cs new file mode 100644 index 0000000..43d02dd --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/SkinningOperator.cs @@ -0,0 +1,64 @@ +using UnityEngine; + +namespace LibMMD.Model +{ + public class SkinningOperator + { + public enum SkinningType : byte + { + SkinningBdef1 = 0, + SkinningBdef2 = 1, + SkinningBdef4 = 2, + SkinningSdef = 3 + } + + public abstract class SkinningParam + { + } + + public class Bdef1 : SkinningParam + { + public int BoneId { get; set; } + } + + public class Bdef2 : SkinningParam + { + public Bdef2() + { + BoneId = new int[2]; + } + + public int[] BoneId { get; set; } + public float BoneWeight { get; set; } + } + + public class Bdef4 : SkinningParam + { + public Bdef4() + { + BoneId = new int[4]; + BoneWeight = new float[4]; + } + + public int[] BoneId { get; set; } + public float[] BoneWeight { get; set; } + } + + public class Sdef : SkinningParam + { + public Sdef() + { + BoneId = new int[2]; + } + + public int[] BoneId { get; set; } + public float BoneWeight { get; set; } + public Vector3 C { get; set; } + public Vector3 R0 { get; set; } + public Vector3 R1 { get; set; } + } + + public SkinningType Type { get; set; } + public SkinningParam Param { get; set; } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/SkinningOperator.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/SkinningOperator.cs.meta new file mode 100644 index 0000000..24636aa --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/SkinningOperator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fcf11bb8f382aff4d8e67cd1d879439e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Vertex.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Vertex.cs new file mode 100644 index 0000000..f0c787b --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Vertex.cs @@ -0,0 +1,14 @@ +using UnityEngine; + +namespace LibMMD.Model +{ + public class Vertex + { + public Vector3 Coordinate { get; set; } + public Vector3 Normal { get; set; } + public Vector2 UvCoordinate { get; set; } + public Vector4[] ExtraUvCoordinate { get; set; } + public SkinningOperator SkinningOperator { get; set; } + public float EdgeScale { get; set; } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Vertex.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Vertex.cs.meta new file mode 100644 index 0000000..51407f4 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Model/Vertex.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a8dee8727f3427b4eab957bef13ea4b6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader.meta new file mode 100644 index 0000000..f2e8d14 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 880762e0e6c9b294894eb766068a3dad +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ByteArrayReader.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ByteArrayReader.cs new file mode 100644 index 0000000..4906d8c --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ByteArrayReader.cs @@ -0,0 +1,32 @@ +using System; + +namespace LibMMD.Unity3D +{ + public class ByteArrayReader + { + public static int ReadInt(byte[] data, ref int offset) { + var ret = BitConverter.ToInt32(data, offset); + offset += 4; + return ret; + } + + public static uint ReadUInt(byte[] data, ref int offset) { + var ret = BitConverter.ToUInt32(data, offset); + offset += 4; + return ret; + } + + public static short ReadShort(byte[] data, ref int offset) { + var ret = BitConverter.ToInt16(data, offset); + offset += 2; + return ret; + } + + public static ushort ReadUShort(byte[] data, ref int offset) { + var ret = BitConverter.ToUInt16(data, offset); + offset += 2; + return ret; + } + } +} + diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ByteArrayReader.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ByteArrayReader.cs.meta new file mode 100644 index 0000000..7f7649a --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ByteArrayReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 644ea355b01ce9e4a9bc31a2e4b08131 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/MMDFileParseException.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/MMDFileParseException.cs new file mode 100644 index 0000000..aecbc89 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/MMDFileParseException.cs @@ -0,0 +1,11 @@ +using System; + +namespace LibMMD.Reader +{ + public class MMDFileParseException : Exception + { + public MMDFileParseException(string message) : base(message) + { + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/MMDFileParseException.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/MMDFileParseException.cs.meta new file mode 100644 index 0000000..6e5836f --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/MMDFileParseException.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7ca57088506381e4bb6d98196ff14be2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ModelReadConfig.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ModelReadConfig.cs new file mode 100644 index 0000000..0b096ff --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ModelReadConfig.cs @@ -0,0 +1,7 @@ +namespace LibMMD.Reader +{ + public class ModelReadConfig + { + public string GlobalToonPath { get; set; } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ModelReadConfig.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ModelReadConfig.cs.meta new file mode 100644 index 0000000..a3edd74 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ModelReadConfig.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: beb1a7fbb7deca44c9cf8f9f4b0c2b10 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ModelReader.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ModelReader.cs new file mode 100644 index 0000000..5e3d3a1 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ModelReader.cs @@ -0,0 +1,39 @@ +using System.IO; +using LibMMD.Model; + +namespace LibMMD.Reader +{ + public abstract class ModelReader + { + public RawMMDModel Read(string path, ModelReadConfig config) + { + using (var fileStream = new FileStream(path, FileMode.Open)) + { + using (var bufferedStream = new BufferedStream(fileStream)) { + using (var binaryReader = new BinaryReader(bufferedStream)) + { + return Read(binaryReader, config); + } + } + } + } + + public abstract RawMMDModel Read(BinaryReader reader, ModelReadConfig config); + + public static RawMMDModel LoadMmdModel(string path, ModelReadConfig config) + { + var fileExt = new FileInfo(path).Extension.ToLower(); + if (".pmd".Equals(fileExt)) + { + return new PMDReader().Read(path, config); + } + if (".pmx".Equals(fileExt)) + { + return new PMXReader().Read(path, config); + } + throw new MMDFileParseException("File " + path + + " is not a MMD model file. File name should ends with \"pmd\" or \"pmx\"."); + } + + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ModelReader.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ModelReader.cs.meta new file mode 100644 index 0000000..c152fc0 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/ModelReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c21137d135f1bba43b2de5ae8f7d0f45 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/PMDReader.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/PMDReader.cs new file mode 100644 index 0000000..6027059 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/PMDReader.cs @@ -0,0 +1,730 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using LibMMD.Material; +using LibMMD.Model; +using LibMMD.Util; +using UnityEngine; + +namespace LibMMD.Reader +{ + public class PMDReader : ModelReader + { + public override RawMMDModel Read(BinaryReader reader, ModelReadConfig config) + { + var model = new RawMMDModel(); + var context = new PmdReadContext(); + var meta = ReadMeta(reader); + if (!"Pmd".Equals(meta.Magic) || Math.Abs(meta.Version - 1.0f) > 0.0001f) + { + throw new MMDFileParseException("File is not a PMD 1.0 file"); + } + ReadDescription(reader, model); + ReadVertices(reader, model); + ReadTriangles(reader, model); + var toonTextureIds = new List(); + ReadParts(reader, model, toonTextureIds); + ReadBonesAndIks(reader, model, context); + ReadFaces(reader, model); + ReadFacdDisplayListNames(reader); + ReadBoneNameList(reader, context); + ReadBoneDisp(reader); + if (MMDReaderUtil.Eof(reader)) + { + goto PMD_READER_READ_LEGACY_30; + } + ReadInfoEn(reader, model, context); + if (MMDReaderUtil.Eof(reader)) + { + goto PMD_READER_READ_LEGACY_30; + } + ReadCustomTextures(reader, config, model, toonTextureIds); + if (MMDReaderUtil.Eof(reader)) + { + goto PMD_READER_READ_LEGACY_50; + } + ReadRigidBodies(reader, model, context); + ReadConstraints(reader, model); + goto PMD_READER_READ_SUCCEED; + + PMD_READER_READ_LEGACY_30: + + for (var i = 0; i < model.Parts.Length; ++i) + { + var material = model.Parts[i].Material; + material.Toon = MMDTextureUtil.GetGlobalToon(toonTextureIds[i], config.GlobalToonPath); + } + PMD_READER_READ_LEGACY_50: + PMD_READER_READ_SUCCEED: + model.Normalize(); + return model; + } + + private static void ReadConstraints(BinaryReader reader, RawMMDModel model) + { + var constraintNum = reader.ReadUInt32(); + model.Joints = new Model.Joint[constraintNum]; + for (var i = 0; i < constraintNum; ++i) + { + var constraint = new Model.Joint(); + constraint.Name = MMDReaderUtil.ReadStringFixedLength(reader, 20, Tools.JapaneseEncoding); + constraint.AssociatedRigidBodyIndex[0] = reader.ReadInt32(); + constraint.AssociatedRigidBodyIndex[1] = reader.ReadInt32(); + constraint.Position = MMDReaderUtil.ReadVector3(reader); + constraint.Rotation = MMDReaderUtil.ReadAmpVector3(reader, Mathf.Rad2Deg); + constraint.PositionLowLimit = MMDReaderUtil.ReadVector3(reader); + constraint.PositionHiLimit = MMDReaderUtil.ReadVector3(reader); + constraint.RotationLowLimit = MMDReaderUtil.ReadVector3(reader); + constraint.RotationHiLimit = MMDReaderUtil.ReadVector3(reader); + constraint.SpringTranslate = MMDReaderUtil.ReadVector3(reader); + constraint.SpringRotate = MMDReaderUtil.ReadVector3(reader); + model.Joints[i] = constraint; + } + } + + private static void ReadRigidBodies(BinaryReader reader, RawMMDModel model, PmdReadContext context) + { + var rigidBodyNum = reader.ReadInt32(); + model.Rigidbodies = new MMDRigidBody[rigidBodyNum]; + for (var i = 0; i < rigidBodyNum; ++i) + { + var rigidBody = new MMDRigidBody(); + + rigidBody.Name = MMDReaderUtil.ReadStringFixedLength(reader, 20, Tools.JapaneseEncoding).Trim(); + var boneIndex = reader.ReadUInt16(); + if (boneIndex < context.BoneNum) + { + rigidBody.AssociatedBoneIndex = boneIndex; + } + else + { + if (context.CenterBoneIndex == null) + { + rigidBody.AssociatedBoneIndex = 0; + } + else + { + rigidBody.AssociatedBoneIndex = context.CenterBoneIndex.Value; + } + } + rigidBody.CollisionGroup = reader.ReadSByte(); + rigidBody.CollisionMask = reader.ReadUInt16(); + rigidBody.Shape = (MMDRigidBody.RigidBodyShape) reader.ReadByte(); + rigidBody.Dimemsions = MMDReaderUtil.ReadVector3(reader); + var rbPosition = MMDReaderUtil.ReadVector3(reader); + rigidBody.Position = model.Bones[rigidBody.AssociatedBoneIndex].Position + rbPosition; + rigidBody.Rotation = MMDReaderUtil.ReadVector3(reader); + rigidBody.Mass = reader.ReadSingle(); + rigidBody.TranslateDamp = reader.ReadSingle(); + rigidBody.RotateDamp = reader.ReadSingle(); + rigidBody.Restitution = reader.ReadSingle(); + rigidBody.Friction = reader.ReadSingle(); + + var type = reader.ReadByte(); + if (boneIndex < context.BoneNum) + { + rigidBody.Type = (MMDRigidBody.RigidBodyType) type; + } + else + { + rigidBody.Type = MMDRigidBody.RigidBodyType.RigidTypePhysicsGhost; + } + model.Rigidbodies[i] = rigidBody; + } + } + + private static void ReadCustomTextures(BinaryReader reader, ModelReadConfig config, RawMMDModel model, + List toonTextureIds) + { + var customTextures = new MMDTexture[10]; + for (var i = 0; i < 10; ++i) + { + customTextures[i] = + new MMDTexture(MMDReaderUtil.ReadStringFixedLength(reader, 100, Tools.JapaneseEncoding)); + } + + for (var i = 0; i < model.Parts.Length; ++i) + { + var material = model.Parts[i].Material; + if (toonTextureIds[i] < 10) + { + material.Toon = customTextures[toonTextureIds[i]]; + } + else + { + material.Toon = MMDTextureUtil.GetGlobalToon(0, config.GlobalToonPath); + } + } + } + + private static void ReadInfoEn(BinaryReader reader, RawMMDModel model, PmdReadContext context) + { + var hasInfoEn = reader.ReadSByte() == 1; + if (!hasInfoEn) return; + model.NameEn = MMDReaderUtil.ReadStringFixedLength(reader, 20, Tools.JapaneseEncoding); + model.DescriptionEn = MMDReaderUtil.ReadStringFixedLength(reader, 256, Tools.JapaneseEncoding); + + for (var i = 0; i < context.BoneNum; ++i) + { + var bone = model.Bones[i]; + bone.NameEn = MMDReaderUtil.ReadStringFixedLength(reader, 20, Tools.JapaneseEncoding); + } + + if (model.Morphs.Length > 0) + { + model.Morphs[0].NameEn = model.Morphs[0].Name; + } + for (var i = 1; i < model.Morphs.Length; ++i) + { + var morph = model.Morphs[i]; + morph.NameEn = MMDReaderUtil.ReadStringFixedLength(reader, 20, Tools.JapaneseEncoding); + } + + // UNDONE + for (var i = 0; i < context.BoneNameListNum; ++i) + { + MMDReaderUtil.ReadStringFixedLength(reader, 50, Tools.JapaneseEncoding); + } + } + + private static void ReadBoneDisp(BinaryReader reader) + { + var boneDispNum = reader.ReadInt32(); + for (var i = 0; i < boneDispNum; ++i) + { + reader.ReadUInt16(); + reader.ReadSByte(); + } + } + + private static void ReadBoneNameList(BinaryReader reader, PmdReadContext context) + { + int boneNameListNum = reader.ReadSByte(); + context.BoneNameListNum = boneNameListNum; + for (var i = 0; i < boneNameListNum; ++i) + { + MMDReaderUtil.ReadStringFixedLength(reader, 50, Tools.JapaneseEncoding); + } + } + + private static void ReadFacdDisplayListNames(BinaryReader reader) + { + int faceDisplayListName = reader.ReadSByte(); + for (var i = 0; i < faceDisplayListName; ++i) + { + reader.ReadUInt16(); + } + } + + private void ReadFaces(BinaryReader reader, RawMMDModel model) + { + var faceNum = reader.ReadUInt16(); + int? baseMorphIndex = null; + model.Morphs = new Morph[faceNum]; + for (var i = 0; i < faceNum; ++i) + { + var morph = new Morph(); + var fp = ReadPmdFacePreamble(reader); + morph.Name = fp.Name; + morph.Category = (Morph.MorphCategory) fp.FaceType; + if (morph.Category == Morph.MorphCategory.MorphCatSystem) + { + baseMorphIndex = i; + } + morph.Type = Morph.MorphType.MorphTypeVertex; + morph.MorphDatas = new Morph.MorphData[fp.VertexNum]; + for (var j = 0; j < fp.VertexNum; ++j) + { + var vertexMorphData = new Morph.VertexMorphData(); + vertexMorphData.VertexIndex = reader.ReadInt32(); + vertexMorphData.Offset = MMDReaderUtil.ReadVector3(reader); + morph.MorphDatas[j] = vertexMorphData; + } + model.Morphs[i] = morph; + } + + if (baseMorphIndex != null) + { + var baseMorph = model.Morphs[baseMorphIndex.Value]; + for (var i = 0; i < faceNum; ++i) + { + if (i == baseMorphIndex) + { + continue; + } + var morph = model.Morphs[i]; + for (var j = 0; j < morph.MorphDatas.Length; ++j) + { + var vertexMorphData = (Morph.VertexMorphData) morph.MorphDatas[j]; + var morphDataVertexIndex = vertexMorphData.VertexIndex; + vertexMorphData.VertexIndex = ((Morph.VertexMorphData) baseMorph.MorphDatas[morphDataVertexIndex]) + .VertexIndex; + } + } + } + } + + private PmdFacePreamble ReadPmdFacePreamble(BinaryReader reader) + { + return new PmdFacePreamble + { + Name = MMDReaderUtil.ReadStringFixedLength(reader, 20, Tools.JapaneseEncoding), + VertexNum = reader.ReadInt32(), + FaceType = reader.ReadSByte() + }; + } + + private void ReadBonesAndIks(BinaryReader reader, RawMMDModel model, PmdReadContext context) + { + int boneNum = reader.ReadUInt16(); + context.BoneNum = boneNum; + var rawBones = new PmdBone[boneNum]; + for (var i = 0; i < boneNum; ++i) + { + rawBones[i] = ReadPmdBone(reader); + } + + var ikBoneIds = new HashSet(); + int ikNum = reader.ReadUInt16(); + var rawIkList = new List(ikNum); + for (var i = 0; i < ikNum; ++i) + { + var rawIk = new PmdRawIk(); + rawIk.Preamble = ReadPmdIkPreamable(reader); + ikBoneIds.Add(rawIk.Preamble.IkBoneIndex); + rawIk.Chain = new int[rawIk.Preamble.IkChainLength]; + for (var j = 0; j < rawIk.Preamble.IkChainLength; ++j) + { + rawIk.Chain[j] = reader.ReadUInt16(); + } + rawIkList.Add(rawIk); + } + + rawIkList.Sort((ik1, ik2) => + { + var a1 = 0; + var a2 = 0; + if (ik1.Chain.Length > 0) + { + a1 = ik1.Chain[0]; + } + if (ik2.Chain.Length > 0) + { + a2 = ik2.Chain[0]; + } + return a1.CompareTo(a2); + }); + + var boneList = new List(); + + int? centerBoneIndex = null; + model.Bones = new Bone[boneNum]; + for (var i = 0; i < boneNum; ++i) + { + var bone = new Bone(); + boneList.Add(bone); + var rawBone = rawBones[i]; + bone.Name = rawBone.Name; + if ("\u30BB\u30F3\u30BF\u30FC".Equals(bone.Name)) //TODO 验证是不是这个值 + { + centerBoneIndex = i; + } + bone.Position = rawBone.Position; + // TODO - workaround here, need fix, see [1]. + if (i != rawBone.ParentId) + { + bone.ParentIndex = rawBone.ParentId; + } + else + { + bone.ParentIndex = 0; //TODO mmdlib里是nil + } + bone.TransformLevel = 0; + bone.ChildBoneVal.ChildUseId = true; + bone.ChildBoneVal.Index = rawBone.ChildId; + bone.Rotatable = true; + var type = (PmdBoneTypes) rawBone.Type; + bone.HasIk = type == PmdBoneTypes.PmdBoneIk || ikBoneIds.Contains(i); + bone.Movable = type == PmdBoneTypes.PmdBoneRotateAndTranslate || bone.HasIk; + bone.Visible = type != PmdBoneTypes.PmdBoneIkTo && type != PmdBoneTypes.PmdBoneInvisible && + type != PmdBoneTypes.PmdBoneRotateRatio; + bone.Controllable = true; + bone.AppendRotate = type == PmdBoneTypes.PmdBoneRotateEffect || type == PmdBoneTypes.PmdBoneRotateRatio; + bone.AppendTranslate = false; + bone.RotAxisFixed = type == PmdBoneTypes.PmdBoneTwist; + bone.UseLocalAxis = false; + bone.PostPhysics = false; + bone.ReceiveTransform = false; + + if (bone.AppendRotate) + { + if (type == PmdBoneTypes.PmdBoneRotateEffect) + { + bone.AppendBoneVal.Index = rawBone.IkNumber; + bone.AppendBoneVal.Ratio = 1.0f; + bone.TransformLevel = 2; + } + else + { + bone.ChildBoneVal.ChildUseId = false; + bone.ChildBoneVal.Offset = Vector3.zero; + bone.AppendBoneVal.Index = rawBone.ChildId; + bone.AppendBoneVal.Ratio = rawBone.IkNumber * 0.01f; + } + } + if (bone.HasIk) + { + bone.TransformLevel = 1; + } + + if (bone.RotAxisFixed) + { + var childId = rawBone.ChildId; + if (childId > boneNum) + { + childId = 0; + } + bone.RotAxis = (rawBones[childId].Position - bone.Position).normalized; + if (bone.ChildBoneVal.ChildUseId) + { + bone.ChildBoneVal.ChildUseId = false; + bone.ChildBoneVal.Offset = Vector3.zero; + } + } + + model.Bones[i] = bone; + } + + var loLimit = Vector3.zero; + var hiLimit = Vector3.zero; + loLimit.x = (float) -Math.PI; + hiLimit.x = (float) (-0.5f / 180.0f * Math.PI); + + for (var i = 0; i < boneNum; ++i) + { + if (!ikBoneIds.Contains(i)) + { + boneList[i].IkInfoVal = new Bone.IkInfo + { + IkLinks = new Bone.IkLink[0] + }; + continue; + } + var associatedIkCount = 0; + for (var j = 0; j < ikNum; ++j) + { + var rawIk = rawIkList[j]; + if (i != rawIk.Preamble.IkBoneIndex) + { + continue; + } + Bone bone; + if (associatedIkCount == 0) + { + bone = boneList[i]; + } + else + { + var originalBone = boneList[i]; + bone = Bone.CopyOf(originalBone); + boneList.Add(bone); + bone.Name = "[IK]" + originalBone.Name; + bone.NameEn = "[IK]" + originalBone.NameEn; + bone.ParentIndex = i; + bone.ChildBoneVal.ChildUseId = false; + bone.ChildBoneVal.Offset = Vector3.zero; + bone.Visible = false; + bone.IkInfoVal.IkLinks = new Bone.IkLink[rawIk.Preamble.IkChainLength]; + bone.HasIk = true; + } + bone.IkInfoVal = new Bone.IkInfo(); + bone.IkInfoVal.IkTargetIndex = rawIk.Preamble.IkTargetBoneIndex; + bone.IkInfoVal.CcdIterateLimit = rawIk.Preamble.CcdIterateLimit; + bone.IkInfoVal.CcdAngleLimit = rawIk.Preamble.CcdAngleLimit; + bone.IkInfoVal.IkLinks = new Bone.IkLink[rawIk.Preamble.IkChainLength]; + + for (var k = 0; k < rawIk.Preamble.IkChainLength; ++k) + { + var link = new Bone.IkLink(); + link.LinkIndex = rawIk.Chain[k]; + var linkName = model.Bones[link.LinkIndex].Name; + if ("\u5DE6\u3072\u3056".Equals(linkName) || "\u53F3\u3072\u3056".Equals(linkName)) + { + link.HasLimit = true; + link.LoLimit = loLimit; + link.HiLimit = hiLimit; + } + else + { + link.HasLimit = false; + } + + bone.IkInfoVal.IkLinks[k] = link; + } + + associatedIkCount++; + } + } + + model.Bones = boneList.ToArray(); + + // TODO - need verification + + for (var i = 0; i < boneNum; ++i) + { + var stable = true; + for (var j = 0; j < boneNum; ++j) + { + var bone = model.Bones[j]; + var transformLevel = bone.TransformLevel; + var parentId = bone.ParentIndex; + while (parentId < boneNum) + { + var parentTransformLevel = model.Bones[parentId].TransformLevel; + if (transformLevel < parentTransformLevel) + { + transformLevel = parentTransformLevel; + stable = false; + } + parentId = model.Bones[parentId].ParentIndex; + } + bone.TransformLevel = transformLevel; + } + if (stable) + { + break; + } + } + context.CenterBoneIndex = centerBoneIndex; + } + + private static void ReadParts(BinaryReader reader, RawMMDModel model, List tooTextureIds) + { + var partNum = reader.ReadInt32(); + var partBaseShift = 0; + model.Parts = new Part[partNum]; + for (var i = 0; i < partNum; ++i) + { + var material = new MMDMaterial(); + material.DiffuseColor = MMDReaderUtil.ReadColor(reader, true); + material.Shiness = reader.ReadSingle(); + material.SpecularColor = MMDReaderUtil.ReadColor(reader, false); + material.AmbientColor = MMDReaderUtil.ReadColor(reader, false); + var toonId = reader.ReadByte(); + var edgeFlag = reader.ReadSByte(); + var vertexNum = reader.ReadInt32(); + var textureName = MMDReaderUtil.ReadStringFixedLength(reader, 20, Tools.JapaneseEncoding); + material.DrawDoubleFace = material.DiffuseColor.a < 0.9999f; + material.DrawGroundShadow = edgeFlag != 0; + material.CastSelfShadow = true; + material.DrawSelfShadow = true; + material.DrawEdge = edgeFlag != 0; + material.EdgeColor = Color.black; + if (!string.IsNullOrEmpty(textureName)) + { + var dlmPos = textureName.IndexOf("*", StringComparison.Ordinal); + if (dlmPos >= 0) + { + var texPath = textureName.Substring(0, dlmPos); + var sphPath = textureName.Substring(dlmPos + 1); + if (!string.IsNullOrEmpty(texPath)) + { + material.Texture = new MMDTexture(texPath); + } + if (!string.IsNullOrEmpty(sphPath)) + { + material.SubTexture = new MMDTexture(sphPath); + } + if (sphPath.EndsWith("a") || sphPath.EndsWith("A")) + { + material.SubTextureType = MMDMaterial.SubTextureTypeEnum.MatSubTexSpa; + } + else + { + material.SubTextureType = MMDMaterial.SubTextureTypeEnum.MatSubTexSph; + } + } + else + { + var extDlmPos = textureName.LastIndexOf(".", StringComparison.Ordinal); + if (extDlmPos >= 0) + { + var ext = textureName.Substring(extDlmPos + 1); + ext = ext.ToLower(); + if (!ext.Equals("sph") && !ext.Equals("spa")) + { + material.Texture = new MMDTexture(textureName); + } + else + { + material.SubTexture = new MMDTexture(textureName); + ; + if (ext.EndsWith("a")) + { + material.SubTextureType = MMDMaterial.SubTextureTypeEnum.MatSubTexSpa; + } + else + { + material.SubTextureType = MMDMaterial.SubTextureTypeEnum.MatSubTexSph; + } + } + } + else + { + material.Texture = new MMDTexture(textureName); + } + } + } + var part = new Part(); + part.Material = material; + tooTextureIds.Add(toonId); + part.BaseShift = partBaseShift; + part.TriangleIndexNum = vertexNum; + partBaseShift += vertexNum; + model.Parts[i] = part; + } + } + + private static void ReadTriangles(BinaryReader reader, RawMMDModel model) + { + var triangleIndexCount = reader.ReadInt32(); + model.TriangleIndexes = new int[triangleIndexCount]; + if (triangleIndexCount % 3 != 0) + { + throw new MMDFileParseException("triangle index count " + triangleIndexCount + " is not multiple of 3"); + } + for (var i = 0; i < triangleIndexCount; ++i) + { + model.TriangleIndexes[i] = reader.ReadUInt16(); + } + } + + private static void ReadVertices(BinaryReader reader, RawMMDModel model) + { + var vertexNum = reader.ReadInt32(); + model.Vertices = new Vertex[vertexNum]; + for (var i = 0; i < vertexNum; ++i) + { + var vertex = new Vertex + { + Coordinate = MMDReaderUtil.ReadVector3(reader), + Normal = MMDReaderUtil.ReadVector3(reader), + UvCoordinate = MMDReaderUtil.ReadVector2(reader) + }; + var skinningOperator = new SkinningOperator(); + var bdef2 = new SkinningOperator.Bdef2(); + bdef2.BoneId = new int[2]; + bdef2.BoneId[0] = reader.ReadInt16(); + bdef2.BoneId[1] = reader.ReadInt16(); + bdef2.BoneWeight = reader.ReadSByte() * 0.01f; + skinningOperator.Param = bdef2; + skinningOperator.Type = SkinningOperator.SkinningType.SkinningBdef2; + vertex.SkinningOperator = skinningOperator; + var noEdge = reader.ReadByte() != 0; + vertex.EdgeScale = noEdge ? 0.0f : 1.0f; + model.Vertices[i] = vertex; + } + } + + + private static void ReadDescription(BinaryReader reader, RawMMDModel model) + { + model.Name = MMDReaderUtil.ReadStringFixedLength(reader, 20, Tools.JapaneseEncoding); + model.Description = MMDReaderUtil.ReadStringFixedLength(reader, 256, Tools.JapaneseEncoding); + } + + private static PmdMeta ReadMeta(BinaryReader reader) + { + PmdMeta ret; + ret.Magic = MMDReaderUtil.ReadStringFixedLength(reader, 3, Encoding.ASCII); + ret.Version = reader.ReadSingle(); + return ret; + } + + private struct PmdMeta + { + public string Magic; + public float Version; + } + + private PmdBone ReadPmdBone(BinaryReader reader) + { + return new PmdBone + { + Name = MMDReaderUtil.ReadStringFixedLength(reader, 20, Tools.JapaneseEncoding), + ParentId = reader.ReadUInt16(), + ChildId = reader.ReadUInt16(), + Type = reader.ReadSByte(), + IkNumber = reader.ReadUInt16(), + Position = MMDReaderUtil.ReadVector3(reader) + }; + } + + private PmdIkPreamble ReadPmdIkPreamable(BinaryReader reader) + { + return new PmdIkPreamble + { + IkBoneIndex = reader.ReadInt16(), + IkTargetBoneIndex = reader.ReadInt16(), + IkChainLength = reader.ReadSByte(), + CcdIterateLimit = reader.ReadUInt16(), + CcdAngleLimit = reader.ReadSingle() + }; + } + + + private class PmdBone + { + public string Name { get; set; } + public ushort ParentId { get; set; } + public ushort ChildId { get; set; } + public sbyte Type { get; set; } + public ushort IkNumber { get; set; } + public Vector3 Position { get; set; } + } + + private class PmdIkPreamble + { + public short IkBoneIndex { get; set; } + public short IkTargetBoneIndex { get; set; } + public sbyte IkChainLength { get; set; } + public ushort CcdIterateLimit { get; set; } + public float CcdAngleLimit { get; set; } + } + + private class PmdRawIk + { + public PmdIkPreamble Preamble { get; set; } + public int[] Chain { get; set; } + } + + private enum PmdBoneTypes : byte + { + PmdBoneRotate = 0, + PmdBoneRotateAndTranslate = 1, + PmdBoneIk = 2, + PmdBoneUnknown = 3, + PmdBoneIkLink = 4, + PmdBoneRotateEffect = 5, + PmdBoneIkTo = 6, + PmdBoneInvisible = 7, + PmdBoneTwist = 8, + PmdBoneRotateRatio = 9 + } + + private class PmdFacePreamble + { + public string Name { get; set; } + public int VertexNum { get; set; } + public sbyte FaceType { get; set; } + } + + private class PmdReadContext + { + public int? CenterBoneIndex { get; set; } + public int BoneNum { get; set; } + public int BoneNameListNum { get; set; } + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/PMDReader.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/PMDReader.cs.meta new file mode 100644 index 0000000..a715155 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/PMDReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 719b4729c95822f45aff8f670135851b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/PMXReader.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/PMXReader.cs new file mode 100644 index 0000000..f55b109 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/PMXReader.cs @@ -0,0 +1,627 @@ +using System; +using System.IO; +using System.Text; +using LibMMD.Material; +using LibMMD.Model; +using LibMMD.Util; +using UnityEngine; + +namespace LibMMD.Reader +{ + public class PMXReader : ModelReader + { + const float JointSplingAmp = 0.08f; + const float JointDampAmp = 0.08f; + + public override RawMMDModel Read(BinaryReader reader, ModelReadConfig config) + { + PmxMeta pmxHeader; + try + { + pmxHeader = ReadMeta(reader); + } + catch + { + throw new MMDFileParseException("Could not read pmx meta data."); + } + + if (!"PMX ".Equals(pmxHeader.Magic) || Math.Abs(pmxHeader.Version - 2.0f) > 0.0001f || pmxHeader.FileFlagSize !=8) + { + throw new MMDFileParseException("File is not a PMX 2.0 file"); + } + + var model = new RawMMDModel(); + var pmxConfig = ReadPmxConfig(reader, model); + ReadModelNameAndDescription(reader, model, pmxConfig); + ReadVertices(reader, model, pmxConfig); + ReadTriangles(reader, model, pmxConfig); + var textureList = ReadTextureList(reader, pmxConfig); + ReadParts(reader, config, model, pmxConfig, textureList); + ReadBones(reader, model, pmxConfig); + ReadMorphs(reader, model, pmxConfig); + ReadEntries(reader, pmxConfig); + ReadRigidBodies(reader, model, pmxConfig); + ReadJoints(reader, model, pmxConfig); + model.Normalize(); + return model; + } + + private static void ReadJoints(BinaryReader reader, RawMMDModel model, PmxConfig pmxConfig) + { + var constraintNum = reader.ReadInt32(); + model.Joints = new Model.Joint[constraintNum]; + for (var i = 0; i < constraintNum; ++i) + { + var joint = new Model.Joint + { + Name = MMDReaderUtil.ReadSizedString(reader, pmxConfig.Encoding), + NameEn = MMDReaderUtil.ReadSizedString(reader, pmxConfig.Encoding) + }; + var dofType = reader.ReadByte(); + if (dofType == 0) + { + joint.AssociatedRigidBodyIndex[0] = + MMDReaderUtil.ReadIndex(reader, pmxConfig.RigidBodyIndexSize); + joint.AssociatedRigidBodyIndex[1] = + MMDReaderUtil.ReadIndex(reader, pmxConfig.RigidBodyIndexSize); + joint.Position = MMDReaderUtil.ReadVector3(reader); + joint.Rotation = MMDReaderUtil.ReadAmpVector3(reader, Mathf.Rad2Deg); + joint.PositionLowLimit = MMDReaderUtil.ReadVector3(reader); + joint.PositionHiLimit = MMDReaderUtil.ReadVector3(reader); + joint.RotationLowLimit = MMDReaderUtil.ReadVector3(reader); + joint.RotationHiLimit = MMDReaderUtil.ReadVector3(reader); + joint.SpringTranslate = MMDReaderUtil.ReadVector3(reader); + joint.SpringRotate = MMDReaderUtil.ReadVector3(reader); + } + else + { + throw new MMDFileParseException("Only 6DOF spring joints are supported."); + } + + model.Joints[i] = joint; + } + } + + private static PmxConfig ReadPmxConfig(BinaryReader reader, RawMMDModel model) + { + var pmxConfig = new PmxConfig(); + pmxConfig.Utf8Encoding = reader.ReadByte() != 0; + pmxConfig.ExtraUvNumber = reader.ReadSByte(); + pmxConfig.VertexIndexSize = reader.ReadSByte(); + pmxConfig.TextureIndexSize = reader.ReadSByte(); + pmxConfig.MaterialIndexSize = reader.ReadSByte(); + pmxConfig.BoneIndexSize = reader.ReadSByte(); + pmxConfig.MorphIndexSize = reader.ReadSByte(); + pmxConfig.RigidBodyIndexSize = reader.ReadSByte(); + + model.ExtraUvNumber = pmxConfig.ExtraUvNumber; + pmxConfig.Encoding = pmxConfig.Utf8Encoding ? Encoding.UTF8 : Encoding.Unicode; + return pmxConfig; + } + + private static void ReadRigidBodies(BinaryReader reader, RawMMDModel model, PmxConfig pmxConfig) + { + var rigidBodyNum = reader.ReadInt32(); + model.Rigidbodies = new MMDRigidBody[rigidBodyNum]; + for (var i = 0; i < rigidBodyNum; ++i) + { + var rigidBody = new MMDRigidBody + { + Name = MMDReaderUtil.ReadSizedString(reader, pmxConfig.Encoding), + NameEn = MMDReaderUtil.ReadSizedString(reader, pmxConfig.Encoding), + AssociatedBoneIndex = MMDReaderUtil.ReadIndex(reader, pmxConfig.BoneIndexSize), + CollisionGroup = reader.ReadByte(), + CollisionMask = reader.ReadUInt16(), + Shape = (MMDRigidBody.RigidBodyShape) reader.ReadByte(), + Dimemsions = MMDReaderUtil.ReadRawCoordinateVector3(reader), + Position = MMDReaderUtil.ReadVector3(reader), + Rotation = MMDReaderUtil.ReadAmpVector3(reader, Mathf.Rad2Deg), + Mass = reader.ReadSingle(), + TranslateDamp = reader.ReadSingle(), + RotateDamp = reader.ReadSingle(), + Restitution = reader.ReadSingle(), + Friction = reader.ReadSingle(), + Type = (MMDRigidBody.RigidBodyType) reader.ReadByte() + }; + model.Rigidbodies[i] = rigidBody; + } + } + + //unused data + private static void ReadEntries(BinaryReader reader, PmxConfig pmxConfig) + { + var entryItemNum = reader.ReadInt32(); + for (var i = 0; i < entryItemNum; ++i) + { + MMDReaderUtil.ReadSizedString(reader, pmxConfig.Encoding); //entryItemName + MMDReaderUtil.ReadSizedString(reader, pmxConfig.Encoding); //entryItemNameEn + reader.ReadByte(); //isSpecial + var elementNum = reader.ReadInt32(); + for (var j = 0; j < elementNum; ++j) + { + var isMorph = reader.ReadByte() == 1; + if (isMorph) + { + MMDReaderUtil.ReadIndex(reader, pmxConfig.MorphIndexSize); //morphIndex + } + else + { + MMDReaderUtil.ReadIndex(reader, pmxConfig.BoneIndexSize); //boneIndex + } + } + } + } + + private static void ReadMorphs(BinaryReader reader, RawMMDModel model, PmxConfig pmxConfig) + { + var morphNum = reader.ReadInt32(); + int? baseMorphIndex = null; + model.Morphs = new Morph[morphNum]; + for (var i = 0; i < morphNum; ++i) + { + var morph = new Morph + { + Name = MMDReaderUtil.ReadSizedString(reader, pmxConfig.Encoding), + NameEn = MMDReaderUtil.ReadSizedString(reader, pmxConfig.Encoding), + Category = (Morph.MorphCategory) reader.ReadByte() + }; + if (morph.Category == Morph.MorphCategory.MorphCatSystem) + { + baseMorphIndex = i; + } + morph.Type = (Morph.MorphType) reader.ReadByte(); + var morphDataNum = reader.ReadInt32(); + morph.MorphDatas = new Morph.MorphData[morphDataNum]; + switch (morph.Type) + { + case Morph.MorphType.MorphTypeGroup: + for (var j = 0; j < morphDataNum; ++j) + { + var morphData = + new Morph.GroupMorphData + { + MorphIndex = MMDReaderUtil.ReadIndex(reader, pmxConfig.MorphIndexSize), + MorphRate = reader.ReadSingle() + }; + morph.MorphDatas[j] = morphData; + } + break; + case Morph.MorphType.MorphTypeVertex: + for (var j = 0; j < morphDataNum; ++j) + { + var morphData = + new Morph.VertexMorphData + { + VertexIndex = MMDReaderUtil.ReadIndex(reader, pmxConfig.VertexIndexSize), + Offset = MMDReaderUtil.ReadVector3(reader) + }; + morph.MorphDatas[j] = morphData; + } + break; + case Morph.MorphType.MorphTypeBone: + for (var j = 0; j < morphDataNum; ++j) + { + var morphData = + new Morph.BoneMorphData + { + BoneIndex = MMDReaderUtil.ReadIndex(reader, pmxConfig.BoneIndexSize), + Translation = MMDReaderUtil.ReadVector3(reader), + Rotation = MMDReaderUtil.ReadQuaternion(reader) + }; + morph.MorphDatas[j] = morphData; + } + + break; + case Morph.MorphType.MorphTypeUv: + case Morph.MorphType.MorphTypeExtUv1: + case Morph.MorphType.MorphTypeExtUv2: + case Morph.MorphType.MorphTypeExtUv3: + case Morph.MorphType.MorphTypeExtUv4: + for (var j = 0; j < morphDataNum; ++j) + { + var morphData = + new Morph.UvMorphData + { + VertexIndex = MMDReaderUtil.ReadIndex(reader, pmxConfig.VertexIndexSize), + Offset = MMDReaderUtil.ReadVector4(reader) + }; + morph.MorphDatas[j] = morphData; + } + + break; + case Morph.MorphType.MorphTypeMaterial: + for (var j = 0; j < morphDataNum; j++) + { + var morphData = new Morph.MaterialMorphData(); + var mmIndex = MMDReaderUtil.ReadIndex(reader, pmxConfig.MaterialIndexSize); + if (mmIndex < model.Parts.Length && mmIndex > 0) //TODO mmdlib的代码里是和bone数比较。确认这个逻辑 + { + morphData.MaterialIndex = mmIndex; + morphData.Global = false; + } + else + { + morphData.MaterialIndex = 0; + morphData.Global = true; + } + morphData.Method = (Morph.MaterialMorphData.MaterialMorphMethod) reader.ReadByte(); + morphData.Diffuse = MMDReaderUtil.ReadColor(reader, true); + morphData.Specular = MMDReaderUtil.ReadColor(reader, false); + morphData.Shiness = reader.ReadSingle(); + morphData.Ambient = MMDReaderUtil.ReadColor(reader, false); + morphData.EdgeColor = MMDReaderUtil.ReadColor(reader, true); + morphData.EdgeSize = reader.ReadSingle(); + morphData.Texture = MMDReaderUtil.ReadVector4(reader); + morphData.SubTexture = MMDReaderUtil.ReadVector4(reader); + morphData.ToonTexture = MMDReaderUtil.ReadVector4(reader); + morph.MorphDatas[j] = morphData; + } + break; + default: + throw new MMDFileParseException("invalid morph type " + morph.Type); + } + if (baseMorphIndex != null) + { + //TODO rectify system-reserved category + } + + model.Morphs[i] = morph; + } + } + + private static void ReadBones(BinaryReader reader, RawMMDModel model, PmxConfig pmxConfig) + { + var boneNum = reader.ReadInt32(); + model.Bones = new Bone[boneNum]; + for (var i = 0; i < boneNum; ++i) + { + var bone = new Bone + { + Name = MMDReaderUtil.ReadSizedString(reader, pmxConfig.Encoding), + NameEn = MMDReaderUtil.ReadSizedString(reader, pmxConfig.Encoding), + Position = MMDReaderUtil.ReadVector3(reader) + }; + var parentIndex = MMDReaderUtil.ReadIndex(reader, pmxConfig.BoneIndexSize); + if (parentIndex < boneNum && parentIndex >= 0) + { + bone.ParentIndex = parentIndex; + } + else + { + bone.ParentIndex = -1; + } + bone.TransformLevel = reader.ReadInt32(); + var flag = reader.ReadUInt16(); + bone.ChildBoneVal.ChildUseId = (flag & PmxBoneFlags.PmxBoneChildUseId) != 0; + bone.Rotatable = (flag & PmxBoneFlags.PmxBoneRotatable) != 0; + bone.Movable = (flag & PmxBoneFlags.PmxBoneMovable) != 0; + bone.Visible = (flag & PmxBoneFlags.PmxBoneVisible) != 0; + bone.Controllable = (flag & PmxBoneFlags.PmxBoneControllable) != 0; + bone.HasIk = (flag & PmxBoneFlags.PmxBoneHasIk) != 0; + bone.AppendRotate = (flag & PmxBoneFlags.PmxBoneAcquireRotate) != 0; + bone.AppendTranslate = (flag & PmxBoneFlags.PmxBoneAcquireTranslate) != 0; + bone.RotAxisFixed = (flag & PmxBoneFlags.PmxBoneRotAxisFixed) != 0; + bone.UseLocalAxis = (flag & PmxBoneFlags.PmxBoneUseLocalAxis) != 0; + bone.PostPhysics = (flag & PmxBoneFlags.PmxBonePostPhysics) != 0; + bone.ReceiveTransform = (flag & PmxBoneFlags.PmxBoneReceiveTransform) != 0; + if (bone.ChildBoneVal.ChildUseId) + { + bone.ChildBoneVal.Index = MMDReaderUtil.ReadIndex(reader, pmxConfig.BoneIndexSize); + } + else + { + bone.ChildBoneVal.Offset = MMDReaderUtil.ReadVector3(reader); + } + if (bone.RotAxisFixed) + { + bone.RotAxis = MMDReaderUtil.ReadVector3(reader); + } + if (bone.AppendRotate || bone.AppendTranslate) + { + bone.AppendBoneVal.Index = MMDReaderUtil.ReadIndex(reader, pmxConfig.BoneIndexSize); + bone.AppendBoneVal.Ratio = reader.ReadSingle(); + } + if (bone.UseLocalAxis) + { + var localX = MMDReaderUtil.ReadVector3(reader); + var localZ = MMDReaderUtil.ReadVector3(reader); + var localY = Vector3.Cross(localX, localZ); + localZ = Vector3.Cross(localX, localY); + localX.Normalize(); + localY.Normalize(); + localZ.Normalize(); + bone.LocalAxisVal.AxisX = localX; + bone.LocalAxisVal.AxisY = localY; + bone.LocalAxisVal.AxisZ = localZ; + } + if (bone.ReceiveTransform) + { + bone.ExportKey = reader.ReadInt32(); + } + if (bone.HasIk) + { + ReadBoneIk(reader, bone, pmxConfig.BoneIndexSize); + } + + model.Bones[i] = bone; + } + } + + private static void ReadBoneIk(BinaryReader reader, Bone bone, int boneIndexSize) + { + bone.IkInfoVal = new Bone.IkInfo(); + bone.IkInfoVal.IkTargetIndex = MMDReaderUtil.ReadIndex(reader, boneIndexSize); + bone.IkInfoVal.CcdIterateLimit = reader.ReadInt32(); + bone.IkInfoVal.CcdAngleLimit = reader.ReadSingle(); + var ikLinkNum = reader.ReadInt32(); + bone.IkInfoVal.IkLinks = new Bone.IkLink[ikLinkNum]; + for (var j = 0; j < ikLinkNum; ++j) + { + var link = new Bone.IkLink(); + link.LinkIndex = MMDReaderUtil.ReadIndex(reader, boneIndexSize); + link.HasLimit = reader.ReadByte() != 0; + if (link.HasLimit) + { + link.LoLimit = MMDReaderUtil.ReadVector3(reader); + link.HiLimit = MMDReaderUtil.ReadVector3(reader); + } + bone.IkInfoVal.IkLinks[j] = link; + } + } + + private static void ReadParts(BinaryReader reader, ModelReadConfig config, RawMMDModel model, PmxConfig pmxConfig, MMDTexture[] textureList) + { + var partNum = reader.ReadInt32(); + var partBaseShift = 0; + model.Parts = new Part[partNum]; + for (var i = 0; i < partNum; i++) + { + var part = new Part(); + var material = ReadMaterial(reader, config, pmxConfig.Encoding, pmxConfig.TextureIndexSize, textureList); + part.Material = material; + var partTriangleIndexNum = reader.ReadInt32(); + if (partTriangleIndexNum % 3 != 0) + { + throw new MMDFileParseException("part" + i + " triangle index count " + partTriangleIndexNum + + " is not multiple of 3"); + } + part.BaseShift = partBaseShift; + part.TriangleIndexNum = partTriangleIndexNum; + partBaseShift += partTriangleIndexNum; + model.Parts[i] = part; + } + } + + private static MMDTexture[] ReadTextureList(BinaryReader reader, PmxConfig pmxConfig) + { + var textureNum = reader.ReadInt32(); + var textureList = new MMDTexture[textureNum]; + for (var i = 0; i < textureNum; ++i) + { + var texturePathEncoding = pmxConfig.Utf8Encoding ? Encoding.UTF8 : Encoding.Unicode; + var texturePath = MMDReaderUtil.ReadSizedString(reader, texturePathEncoding); + textureList[i] = new MMDTexture(texturePath); + } + return textureList; + } + + private static void ReadTriangles(BinaryReader reader, RawMMDModel model, PmxConfig pmxConfig) + { + var triangleIndexCount = reader.ReadInt32(); + model.TriangleIndexes = new int[triangleIndexCount]; + if (triangleIndexCount % 3 != 0) + { + throw new MMDFileParseException("triangle index count " + triangleIndexCount + " is not multiple of 3"); + } + for (var i = 0; i < triangleIndexCount; ++i) + { + model.TriangleIndexes[i] = MMDReaderUtil.ReadIndex(reader, pmxConfig.VertexIndexSize); + } + } + + private static void ReadVertices(BinaryReader reader, RawMMDModel model, PmxConfig pmxConfig) + { + var vertexNum = reader.ReadInt32(); + model.Vertices = new Vertex[vertexNum]; + for (uint i = 0; i < vertexNum; ++i) + { + var vertex = ReadVertex(reader, pmxConfig); + model.Vertices[i] = vertex; + } + } + + private static void ReadModelNameAndDescription(BinaryReader reader, RawMMDModel model, PmxConfig pmxConfig) + { + model.Name = MMDReaderUtil.ReadSizedString(reader, pmxConfig.Encoding); + model.NameEn = MMDReaderUtil.ReadSizedString(reader, pmxConfig.Encoding); + model.Description = MMDReaderUtil.ReadSizedString(reader, pmxConfig.Encoding); + model.DescriptionEn = MMDReaderUtil.ReadSizedString(reader, pmxConfig.Encoding); + } + + private static Vertex ReadVertex(BinaryReader reader, PmxConfig pmxConfig) + { + var pv = ReadVertexBasic(reader); + var vertex = new Vertex + { + Coordinate = pv.Coordinate, + Normal = pv.Normal, + UvCoordinate = pv.UvCoordinate + }; + + if (pmxConfig.ExtraUvNumber > 0) + { + var extraUv = new Vector4[pmxConfig.ExtraUvNumber]; + for (var ei = 0; ei < pmxConfig.ExtraUvNumber; ++ei) + { + extraUv[ei] = MMDReaderUtil.ReadVector4(reader); + } + vertex.ExtraUvCoordinate = extraUv; + } + + var op = new SkinningOperator(); + var skinningType = (SkinningOperator.SkinningType) reader.ReadByte(); + op.Type = skinningType; + + switch (skinningType) + { + case SkinningOperator.SkinningType.SkinningBdef1: + var bdef1 = new SkinningOperator.Bdef1(); + bdef1.BoneId = MMDReaderUtil.ReadIndex(reader, pmxConfig.BoneIndexSize); + op.Param = bdef1; + break; + case SkinningOperator.SkinningType.SkinningBdef2: + var bdef2 = new SkinningOperator.Bdef2(); + bdef2.BoneId[0] = MMDReaderUtil.ReadIndex(reader, pmxConfig.BoneIndexSize); + bdef2.BoneId[1] = MMDReaderUtil.ReadIndex(reader, pmxConfig.BoneIndexSize); + bdef2.BoneWeight = reader.ReadSingle(); + op.Param = bdef2; + break; + case SkinningOperator.SkinningType.SkinningBdef4: + var bdef4 = new SkinningOperator.Bdef4(); + for (var j = 0; j < 4; ++j) + { + bdef4.BoneId[j] = MMDReaderUtil.ReadIndex(reader, pmxConfig.BoneIndexSize); + } + for (var j = 0; j < 4; ++j) + { + bdef4.BoneWeight[j] = reader.ReadSingle(); + } + op.Param = bdef4; + break; + case SkinningOperator.SkinningType.SkinningSdef: + var sdef = new SkinningOperator.Sdef(); + sdef.BoneId[0] = MMDReaderUtil.ReadIndex(reader, pmxConfig.BoneIndexSize); + sdef.BoneId[1] = MMDReaderUtil.ReadIndex(reader, pmxConfig.BoneIndexSize); + sdef.BoneWeight = reader.ReadSingle(); + sdef.C = MMDReaderUtil.ReadVector3(reader); + sdef.R0 = MMDReaderUtil.ReadVector3(reader); + sdef.R1 = MMDReaderUtil.ReadVector3(reader); + op.Param = sdef; + break; + default: + throw new MMDFileParseException("invalid skinning type: " + skinningType); + } + vertex.SkinningOperator = op; + vertex.EdgeScale = reader.ReadSingle(); + return vertex; + } + + private static MMDMaterial ReadMaterial(BinaryReader reader, ModelReadConfig config, Encoding encoding, + int textureIndexSize, MMDTexture[] textureList) + { + var material = new MMDMaterial(); + material.Name = MMDReaderUtil.ReadSizedString(reader, encoding); + material.NameEn = MMDReaderUtil.ReadSizedString(reader, encoding); + material.DiffuseColor = MMDReaderUtil.ReadColor(reader, true); + material.SpecularColor = MMDReaderUtil.ReadColor(reader, false); + material.Shiness = reader.ReadSingle(); + material.AmbientColor = MMDReaderUtil.ReadColor(reader, false); + var drawFlag = reader.ReadByte(); + material.DrawDoubleFace = (drawFlag & PmxMaterialDrawFlags.PmxMaterialDrawDoubleFace) != 0; + material.DrawGroundShadow = (drawFlag & PmxMaterialDrawFlags.PmxMaterialDrawGroundShadow) != 0; + material.CastSelfShadow = (drawFlag & PmxMaterialDrawFlags.PmxMaterialCastSelfShadow) != 0; + material.DrawSelfShadow = (drawFlag & PmxMaterialDrawFlags.PmxMaterialDrawSelfShadow) != 0; + material.DrawEdge = (drawFlag & PmxMaterialDrawFlags.PmxMaterialDrawEdge) != 0; + material.EdgeColor = MMDReaderUtil.ReadColor(reader, true); + material.EdgeSize = reader.ReadSingle(); + var textureIndex = MMDReaderUtil.ReadIndex(reader, textureIndexSize); + if (textureIndex < textureList.Length && textureIndex >= 0) + { + material.Texture = textureList[textureIndex]; + } + var subTextureIndex = MMDReaderUtil.ReadIndex(reader, textureIndexSize); + if (subTextureIndex < textureList.Length && subTextureIndex >= 0) + { + material.SubTexture = textureList[subTextureIndex]; + } + material.SubTextureType = (MMDMaterial.SubTextureTypeEnum) reader.ReadByte(); + var useGlobalToon = reader.ReadByte() != 0; + if (useGlobalToon) + { + int globalToonIndex = reader.ReadByte(); + material.Toon = MMDTextureUtil.GetGlobalToon(globalToonIndex, config.GlobalToonPath); + } + else + { + var toonIndex = MMDReaderUtil.ReadIndex(reader, textureIndexSize); + if (toonIndex < textureList.Length && toonIndex >= 0) + { + material.Toon = textureList[toonIndex]; + } + } + material.MetaInfo = MMDReaderUtil.ReadSizedString(reader, encoding); + return material; + } + + private static PmxMeta ReadMeta(BinaryReader reader) + { + PmxMeta ret; + ret.Magic = MMDReaderUtil.ReadStringFixedLength(reader, 4, Encoding.ASCII); + ret.Version = reader.ReadSingle(); + ret.FileFlagSize = reader.ReadByte(); + return ret; + } + + private static PmxVertexBasic ReadVertexBasic(BinaryReader reader) + { + PmxVertexBasic ret; + ret.Coordinate = MMDReaderUtil.ReadVector3(reader); + ret.Normal = MMDReaderUtil.ReadVector3(reader); + ret.UvCoordinate = MMDReaderUtil.ReadVector2(reader); + return ret; + } + + + private struct PmxMeta + { + public string Magic; + public float Version; + public byte FileFlagSize; + } + + private struct PmxVertexBasic + { + public Vector3 Coordinate; + public Vector3 Normal; + public Vector2 UvCoordinate; + } + + private class PmxConfig + { + public bool Utf8Encoding { get; set; } + public Encoding Encoding { get; set; } + public int ExtraUvNumber { get; set; } + public int VertexIndexSize { get; set; } + public int TextureIndexSize { get; set; } + public int MaterialIndexSize{ get; set; } + public int BoneIndexSize { get; set; } + public int MorphIndexSize { get; set; } + public int RigidBodyIndexSize { get; set; } + } + + private abstract class PmxMaterialDrawFlags + { + public const byte PmxMaterialDrawDoubleFace = 0x01; + public const byte PmxMaterialDrawGroundShadow = 0x02; + public const byte PmxMaterialCastSelfShadow = 0x04; + public const byte PmxMaterialDrawSelfShadow = 0x08; + public const byte PmxMaterialDrawEdge = 0x10; + } + + private abstract class PmxBoneFlags + { + public const ushort PmxBoneChildUseId = 0x0001; + public const ushort PmxBoneRotatable = 0x0002; + public const ushort PmxBoneMovable = 0x0004; + public const ushort PmxBoneVisible = 0x0008; + public const ushort PmxBoneControllable = 0x0010; + public const ushort PmxBoneHasIk = 0x0020; + public const ushort PmxBoneAcquireRotate = 0x0100; + public const ushort PmxBoneAcquireTranslate = 0x0200; + public const ushort PmxBoneRotAxisFixed = 0x0400; + public const ushort PmxBoneUseLocalAxis = 0x0800; + public const ushort PmxBonePostPhysics = 0x1000; + public const ushort PmxBoneReceiveTransform = 0x2000; + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/PMXReader.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/PMXReader.cs.meta new file mode 100644 index 0000000..e42901f --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Reader/PMXReader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3b0fb3bed9b8b8743bc9152bd6cea3ac +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources.meta new file mode 100644 index 0000000..c1ee1db --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f16b59dd6d99a5e4fa38e2b672e92353 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd.meta new file mode 100644 index 0000000..74bd523 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 660944cfede8de84d8945cc950ba37f2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon.meta new file mode 100644 index 0000000..e1d4caa --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1de5827113caaf740b55336c1719eaa1 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon0.bmp b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon0.bmp new file mode 100644 index 0000000000000000000000000000000000000000..1b982fe3b31937dd1894dc3775332a9da4ebb64e GIT binary patch literal 3126 zcmZ?rHRE9b12Z700mKSW%*Y@CWB~zCUWgllAp#5x|3|@S2#kinXb6mkz-S1JhQMeD PjE2By2#kinhzS7zEv5E! literal 0 HcmV?d00001 diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon0.bmp.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon0.bmp.meta new file mode 100644 index 0000000..182232d --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon0.bmp.meta @@ -0,0 +1,112 @@ +fileFormatVersion: 2 +guid: d64ba096e6df12e45a4b226a99353ef2 +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 10 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 1 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -100 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 0 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 2 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + - serializedVersion: 2 + buildTarget: Standalone + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + - serializedVersion: 2 + buildTarget: Android + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon01.bmp b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon01.bmp new file mode 100644 index 0000000000000000000000000000000000000000..08950ab8bd040f2151c8f60baee08aa2e4ceaa47 GIT binary patch literal 3128 zcmZ?rwcud@12Z700mKSW%*Y@CWI=!sHvdRE`Y)>aF zxqs+i_x#moz2kiw?yKGn6|b8sE*0%J{Hx?|bNK)A&D-BYyQ4qwe7`1)W*AMuue60V zO{gbYHk!+A460a$Y zd5XnGSZ;;Y7V8X~9nu_Yl1XR9nuT31%_)8Fr%lLZifnRhcgXfae!z|#u_px%1&+Q_ zu*1IKJ-IjAlrCl58#o)rOB_oSCCVyLRj6vz4$h;39mQ-E1v#CyT{YJ}hY1n_3AC%J ktx2H|HK9wX(Uzb2Dx?|M>Fxx&6X;H$JAv*5{^<$40ijZ@RsaA1 literal 0 HcmV?d00001 diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon05.bmp.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon05.bmp.meta new file mode 100644 index 0000000..c1935a7 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon05.bmp.meta @@ -0,0 +1,112 @@ +fileFormatVersion: 2 +guid: 15cbcd5fb2371d041a1097e22d6d1d19 +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 10 + mipmaps: + mipMapMode: 0 + enableMipMap: 1 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 1 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -100 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 0 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 2 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + - serializedVersion: 2 + buildTarget: Standalone + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + - serializedVersion: 2 + buildTarget: Android + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon06.bmp b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Resources/LibMmd/SysToon/toon06.bmp new file mode 100644 index 0000000000000000000000000000000000000000..9c500c014bfd33b71c114d0ff3ff1a47cbc10e37 GIT binary patch literal 3126 zcmeHHOH30{6s^&^5f#xW#>BXEi=X<7#^5K$=w7}m;Q#;Eg$ok{#*Ml#x^U&nM2m@7 z5D+mD7f1`Oh^a_Kut;0lnSP+3nduzQYpV%~7&V%hIFs{k?%aFcdH0>BQ@GudV@f|3 z#>HHVvTKqlpBW$a^QL81reHEne(=J8;lOV@FtzrjIRk6kls^Hpwar{h2w95fH@oIG zcFlRxnb+W$Rd3I=bOmzZ${yD9(g%NCKJ1Wt^5ptPbN@0w-m01W}pBUJ3gpFdmd} zAkD7|;#L%WD)xPCQRJ|Ung}k2aY{x+hX%xT+>fDB!nG)Lhzg?$*pqN6xEvNIG7f04 z#ZetWV;oWny{dTir{K}xP+*OrH6aE&A3{t=5`yzEhUSDwqB`p1LdUHN8b`W4Dk7PK zngH|mq&T8q!`(4)L{l6$qi9KpBRIyrF?dtxQiL1lLbwt^kCMG9Z^wJlaNd_Wy*ei2 zh@8!7#Zg)C=@{KR8^Q@07eZoA;!;?s-5JI61ZvX5lS~~7(#Bu humanBoneDictionary = new Dictionary(); + + // 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 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 BuildAvatar() + { + // HumanBoneのためのリストを取得する + List humanBones = new List(); + 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.avatar = avatar; + animator.applyRootMotion = true; + animator.runtimeAnimatorController = RuntimeAnimatorController; + return true; + } + + private List GetTransforms(Transform t) + { + SkeletonBone skeletonBone = new SkeletonBone() + { + name = t.name, + position = t.localPosition, + rotation = t.localRotation, + scale = t.localScale + }; + + List singleParentFamily = new List() { skeletonBone }; + + foreach (Transform childT in t) + { + singleParentFamily.AddRange(GetTransforms(childT)); + } + + return singleParentFamily; + } + + private async Task FixBoneWeight() + { + return await FixBoneWeight(skinnedMeshRenderer); + } + + private async Task 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 MakeHumanBoneDictionary(Transform rootTransform, string[] humanBonesContained) + { + Dictionary humanBoneDictionary = new Dictionary(); + 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 MakeHumanBoneDictionary(Transform rootTransform) + { + string[] allBones = (from boneName in HumanTrait.BoneName select MMDModel.Unity_MMDBoneNameDictionary[boneName]).ToArray(); + return MakeHumanBoneDictionary(rootTransform, allBones); + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/AvatarMaker.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/AvatarMaker.cs.meta new file mode 100644 index 0000000..6c3b4ae --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/AvatarMaker.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: aeeb8df58d0fdc04dbcf0663109f4148 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader.meta new file mode 100644 index 0000000..4040e68 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a260ddf6d9b05734fa2dad314acaad9a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/BitmapLoader.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/BitmapLoader.cs new file mode 100644 index 0000000..1015e1c --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/BitmapLoader.cs @@ -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; + } + + } +} + diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/BitmapLoader.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/BitmapLoader.cs.meta new file mode 100644 index 0000000..0fef731 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/BitmapLoader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ae95b04f1bc41da4abfa6ba6aacbd19a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/DDSLoader.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/DDSLoader.cs new file mode 100644 index 0000000..24931a6 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/DDSLoader.cs @@ -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; + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/DDSLoader.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/DDSLoader.cs.meta new file mode 100644 index 0000000..8412192 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/DDSLoader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: fdc931497f191fa4e81c010dee1c43b2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/TargaImage.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/TargaImage.cs new file mode 100644 index 0000000..a91b846 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/TargaImage.cs @@ -0,0 +1,2273 @@ +/** + * This is a modified library from CodeProject: http://www.codeproject.com/Articles/31702/NET-Targa-Image-Reader + * It is modified to remove most .NET dependencies and replaced them with Unity equivilents. This means + * this code should be able to run on all platforms. + * + * No guarantee everything works, but seems to be alright with uncompressed textures. + * It's probably slow, but suits my needs. + * + * Look for "Unity" to see the changes made. + * + * Usage: Texture2D texture = Paloma.TargaImage.LoadTargaImage( "filename.tga" ); + */ + +// ========================================================== +// TargaImage +// +// Design and implementation by +// - David Polomis (paloma_sw@cox.net) +// +// +// This source code, along with any associated files, is licensed under +// The Code Project Open License (CPOL) 1.02 +// A copy of this license can be found in the CPOL.html file +// which was downloaded with this source code +// or at http://www.codeproject.com/info/cpol10.aspx +// +// +// COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, +// WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, +// INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE IS +// FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR +// NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE +// OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE +// DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY +// OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, +// REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN +// ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS +// AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. +// +// Use at your own risk! +// +// ========================================================== + + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace LibMMD.Unity3D.ImageLoader +{ + internal static class TargaConstants + { + // constant byte lengths for various fields in the Targa format + internal const int HeaderByteLength = 18; + internal const int FooterByteLength = 26; + internal const int FooterSignatureOffsetFromEnd = 18; + internal const int FooterSignatureByteLength = 16; + internal const int FooterReservedCharByteLength = 1; + internal const int ExtensionAreaAuthorNameByteLength = 41; + internal const int ExtensionAreaAuthorCommentsByteLength = 324; + internal const int ExtensionAreaJobNameByteLength = 41; + internal const int ExtensionAreaSoftwareIDByteLength = 41; + internal const int ExtensionAreaSoftwareVersionLetterByteLength = 1; + internal const int ExtensionAreaColorCorrectionTableValueLength = 256; + internal const string TargaFooterASCIISignature = "TRUEVISION-XFILE"; + } + + + /// + /// The Targa format of the file. + /// + public enum TGAFormat + { + /// + /// Unknown Targa Image format. + /// + UNKNOWN = 0, + + /// + /// Original Targa Image format. + /// + /// Targa Image does not have a Signature of ""TRUEVISION-XFILE"". + ORIGINAL_TGA = 100, + + /// + /// New Targa Image format + /// + /// Targa Image has a TargaFooter with a Signature of ""TRUEVISION-XFILE"". + NEW_TGA = 200 + } + + + /// + /// Indicates the type of color map, if any, included with the image file. + /// + public enum ColorMapType : byte + { + /// + /// No color map was included in the file. + /// + NO_COLOR_MAP = 0, + + /// + /// Color map was included in the file. + /// + COLOR_MAP_INCLUDED = 1 + } + + + /// + /// The type of image read from the file. + /// + public enum ImageType : byte + { + /// + /// No image data was found in file. + /// + NO_IMAGE_DATA = 0, + + /// + /// Image is an uncompressed, indexed color-mapped image. + /// + UNCOMPRESSED_COLOR_MAPPED = 1, + + /// + /// Image is an uncompressed, RGB image. + /// + UNCOMPRESSED_TRUE_COLOR = 2, + + /// + /// Image is an uncompressed, Greyscale image. + /// + UNCOMPRESSED_BLACK_AND_WHITE = 3, + + /// + /// Image is a compressed, indexed color-mapped image. + /// + RUN_LENGTH_ENCODED_COLOR_MAPPED = 9, + + /// + /// Image is a compressed, RGB image. + /// + RUN_LENGTH_ENCODED_TRUE_COLOR = 10, + + /// + /// Image is a compressed, Greyscale image. + /// + RUN_LENGTH_ENCODED_BLACK_AND_WHITE = 11 + } + + + /// + /// The top-to-bottom ordering in which pixel data is transferred from the file to the screen. + /// + public enum VerticalTransferOrder + { + /// + /// Unknown transfer order. + /// + UNKNOWN = -1, + + /// + /// Transfer order of pixels is from the bottom to top. + /// + BOTTOM = 0, + + /// + /// Transfer order of pixels is from the top to bottom. + /// + TOP = 1 + } + + + /// + /// The left-to-right ordering in which pixel data is transferred from the file to the screen. + /// + public enum HorizontalTransferOrder + { + /// + /// Unknown transfer order. + /// + UNKNOWN = -1, + + /// + /// Transfer order of pixels is from the right to left. + /// + RIGHT = 0, + + /// + /// Transfer order of pixels is from the left to right. + /// + LEFT = 1 + } + + + /// + /// Screen destination of first pixel based on the VerticalTransferOrder and HorizontalTransferOrder. + /// + public enum FirstPixelDestination + { + /// + /// Unknown first pixel destination. + /// + UNKNOWN = 0, + + /// + /// First pixel destination is the top-left corner of the image. + /// + TOP_LEFT = 1, + + /// + /// First pixel destination is the top-right corner of the image. + /// + TOP_RIGHT = 2, + + /// + /// First pixel destination is the bottom-left corner of the image. + /// + BOTTOM_LEFT = 3, + + /// + /// First pixel destination is the bottom-right corner of the image. + /// + BOTTOM_RIGHT = 4 + } + + + /// + /// The RLE packet type used in a RLE compressed image. + /// + public enum RLEPacketType + { + /// + /// A raw RLE packet type. + /// + RAW = 0, + + /// + /// A run-length RLE packet type. + /// + RUN_LENGTH = 1 + } + + + /// + /// Reads and loads a Truevision TGA Format image file. + /// + public class TargaImage + { + private TargaHeader objTargaHeader = null; + private TargaExtensionArea objTargaExtensionArea = null; + private TargaFooter objTargaFooter = null; + private Texture2D bmpTargaImage = null; + private Texture2D bmpImageThumbnail = null; + private TGAFormat eTGAFormat = TGAFormat.UNKNOWN; + private string strFileName = string.Empty; + private int intStride = 0; + private int intPadding = 0; + private List> rows = new List>(); + private List row = new List(); + + /// + /// Creates a new instance of the TargaImage object. + /// + public TargaImage() + { + this.objTargaFooter = new TargaFooter(); + this.objTargaHeader = new TargaHeader(); + this.objTargaExtensionArea = new TargaExtensionArea(); + this.bmpTargaImage = null; + this.bmpImageThumbnail = null; + } + + + /// + /// Gets a TargaHeader object that holds the Targa Header information of the loaded file. + /// + public TargaHeader Header + { + get { return this.objTargaHeader; } + } + + + /// + /// Gets a TargaExtensionArea object that holds the Targa Extension Area information of the loaded file. + /// + public TargaExtensionArea ExtensionArea + { + get { return this.objTargaExtensionArea; } + } + + + /// + /// Gets a TargaExtensionArea object that holds the Targa Footer information of the loaded file. + /// + public TargaFooter Footer + { + get { return this.objTargaFooter; } + } + + + /// + /// Gets the Targa format of the loaded file. + /// + public TGAFormat Format + { + get { return this.eTGAFormat; } + } + + + /// + /// Gets a Bitmap representation of the loaded file. + /// + public Texture Image + { + get { return this.bmpTargaImage; } + } + + /// + /// Gets the thumbnail of the loaded file if there is one in the file. + /// + public Texture Thumbnail + { + get { return this.bmpImageThumbnail; } + } + + /// + /// Gets the full path and filename of the loaded file. + /// + public string FileName + { + get { return this.strFileName; } + } + + + /// + /// Gets the byte offset between the beginning of one scan line and the next. Used when loading the image into the Image Bitmap. + /// + /// + /// The memory allocated for Microsoft Bitmaps must be aligned on a 32bit boundary. + /// The stride refers to the number of bytes allocated for one scanline of the bitmap. + /// + public int Stride + { + get { return this.intStride; } + } + + + /// + /// Gets the number of bytes used to pad each scan line to meet the Stride value. Used when loading the image into the Image Bitmap. + /// + /// + /// The memory allocated for Microsoft Bitmaps must be aligned on a 32bit boundary. + /// The stride refers to the number of bytes allocated for one scanline of the bitmap. + /// In your loop, you copy the pixels one scanline at a time and take into + /// consideration the amount of padding that occurs due to memory alignment. + /// + public int Padding + { + get { return this.intPadding; } + } + + /// + /// Creates a new instance of the TargaImage object with strFileName as the image loaded. + /// + public TargaImage(string strFileName) : this() + { + // make sure we have a .tga file + if (Path.GetExtension(strFileName).ToLower() == ".tga") + { + // make sure the file exists + if (File.Exists(strFileName) == true) + { + this.strFileName = strFileName; + MemoryStream filestream = null; + BinaryReader binReader = null; + byte[] filebytes = null; + + // load the file as an array of bytes + filebytes = File.ReadAllBytes(this.strFileName); + if (filebytes != null && filebytes.Length > 0) + { + // create a seekable memory stream of the file bytes + using (filestream = new MemoryStream(filebytes)) + { + if (filestream != null && filestream.Length > 0 && filestream.CanSeek == true) + { + // create a BinaryReader used to read the Targa file + using (binReader = new BinaryReader(filestream)) + { + this.LoadTGAFooterInfo(binReader); + this.LoadTGAHeaderInfo(binReader); + this.LoadTGAExtensionArea(binReader); + this.LoadTGAImage(binReader); + } + } + else + throw new Exception(@"Error loading file, could not read file from disk."); + + } + + } + else + throw new Exception(@"Error loading file, could not read file from disk."); + + } + else + throw new Exception(@"Error loading file, could not find file '" + strFileName + "' on disk."); + + } + else + throw new Exception(@"Error loading file, file '" + strFileName + "' must have an extension of '.tga'."); + + + } + + + /// + /// Loads the Targa Footer information from the file. + /// + /// A BinaryReader that points the loaded file byte stream. + private void LoadTGAFooterInfo(BinaryReader binReader) + { + + if (binReader != null && binReader.BaseStream != null && binReader.BaseStream.Length > 0 && binReader.BaseStream.CanSeek == true) + { + + try + { + // set the cursor at the beginning of the signature string. + binReader.BaseStream.Seek((TargaConstants.FooterSignatureOffsetFromEnd * -1), SeekOrigin.End); + + // read the signature bytes and convert to ascii string + string Signature = Encoding.ASCII.GetString(binReader.ReadBytes(TargaConstants.FooterSignatureByteLength)).TrimEnd('\0'); + + // do we have a proper signature + if (string.Compare(Signature, TargaConstants.TargaFooterASCIISignature) == 0) + { + // this is a NEW targa file. + // create the footer + this.eTGAFormat = TGAFormat.NEW_TGA; + + // set cursor to beginning of footer info + binReader.BaseStream.Seek((TargaConstants.FooterByteLength * -1), SeekOrigin.End); + + // read the Extension Area Offset value + int ExtOffset = binReader.ReadInt32(); + + // read the Developer Directory Offset value + int DevDirOff = binReader.ReadInt32(); + + // skip the signature we have already read it. + binReader.ReadBytes(TargaConstants.FooterSignatureByteLength); + + // read the reserved character + string ResChar = Encoding.ASCII.GetString(binReader.ReadBytes(TargaConstants.FooterReservedCharByteLength)).TrimEnd('\0'); + + // set all values to our TargaFooter class + this.objTargaFooter.SetExtensionAreaOffset(ExtOffset); + this.objTargaFooter.SetDeveloperDirectoryOffset(DevDirOff); + this.objTargaFooter.SetSignature(Signature); + this.objTargaFooter.SetReservedCharacter(ResChar); + } + else + { + // this is not an ORIGINAL targa file. + this.eTGAFormat = TGAFormat.ORIGINAL_TGA; + } + } + catch ( Exception ex ) + { + // clear all + this.ClearAll(); + throw ex; + } + } + else + { + this.ClearAll(); + throw new Exception(@"Error loading file, could not read file from disk."); + } + + + } + + + /// + /// Loads the Targa Header information from the file. + /// + /// A BinaryReader that points the loaded file byte stream. + private void LoadTGAHeaderInfo(BinaryReader binReader) + { + + if (binReader != null && binReader.BaseStream != null && binReader.BaseStream.Length > 0 && binReader.BaseStream.CanSeek == true) + { + try + { + // set the cursor at the beginning of the file. + binReader.BaseStream.Seek(0, SeekOrigin.Begin); + + // read the header properties from the file + this.objTargaHeader.SetImageIDLength(binReader.ReadByte()); + this.objTargaHeader.SetColorMapType((ColorMapType)binReader.ReadByte()); + this.objTargaHeader.SetImageType((ImageType)binReader.ReadByte()); + + this.objTargaHeader.SetColorMapFirstEntryIndex(binReader.ReadInt16()); + this.objTargaHeader.SetColorMapLength(binReader.ReadInt16()); + this.objTargaHeader.SetColorMapEntrySize(binReader.ReadByte()); + + this.objTargaHeader.SetXOrigin(binReader.ReadInt16()); + this.objTargaHeader.SetYOrigin(binReader.ReadInt16()); + this.objTargaHeader.SetWidth(binReader.ReadInt16()); + this.objTargaHeader.SetHeight(binReader.ReadInt16()); + + byte pixeldepth = binReader.ReadByte(); + switch (pixeldepth) + { + case 8: + case 16: + case 24: + case 32: + this.objTargaHeader.SetPixelDepth(pixeldepth); + break; + + default: + this.ClearAll(); + throw new Exception("Targa Image only supports 8, 16, 24, or 32 bit pixel depths."); + } + + + byte ImageDescriptor = binReader.ReadByte(); + this.objTargaHeader.SetAttributeBits((byte)Utilities.GetBits(ImageDescriptor, 0, 4)); + + this.objTargaHeader.SetVerticalTransferOrder((VerticalTransferOrder)Utilities.GetBits(ImageDescriptor, 5, 1)); + this.objTargaHeader.SetHorizontalTransferOrder((HorizontalTransferOrder)Utilities.GetBits(ImageDescriptor, 4, 1)); + + // load ImageID value if any + if (this.objTargaHeader.ImageIDLength > 0) + { + byte[] ImageIDValueBytes = binReader.ReadBytes(this.objTargaHeader.ImageIDLength); + this.objTargaHeader.SetImageIDValue(Encoding.ASCII.GetString(ImageIDValueBytes).TrimEnd('\0')); + } + } + catch (Exception ex) + { + this.ClearAll(); + throw ex; + } + + + // load color map if it's included and/or needed + // Only needed for UNCOMPRESSED_COLOR_MAPPED and RUN_LENGTH_ENCODED_COLOR_MAPPED + // image types. If color map is included for other file types we can ignore it. + if (this.objTargaHeader.ColorMapType == ColorMapType.COLOR_MAP_INCLUDED) + { + if (this.objTargaHeader.ImageType == ImageType.UNCOMPRESSED_COLOR_MAPPED || + this.objTargaHeader.ImageType == ImageType.RUN_LENGTH_ENCODED_COLOR_MAPPED) + { + if (this.objTargaHeader.ColorMapLength > 0) + { + try + { + for (int i = 0; i < this.objTargaHeader.ColorMapLength; i++) + { + byte a = 0; + byte r = 0; + byte g = 0; + byte b = 0; + + // load each color map entry based on the ColorMapEntrySize value + switch (this.objTargaHeader.ColorMapEntrySize) + { + case 15: + byte[] color15 = binReader.ReadBytes(2); + // remember that the bytes are stored in reverse oreder + this.objTargaHeader.ColorMap.Add(Utilities.GetColorFrom2Bytes(color15[1], color15[0])); + break; + case 16: + byte[] color16 = binReader.ReadBytes(2); + // remember that the bytes are stored in reverse oreder + this.objTargaHeader.ColorMap.Add(Utilities.GetColorFrom2Bytes(color16[1], color16[0])); + break; + case 24: + b = binReader.ReadByte(); + g = binReader.ReadByte(); + r = binReader.ReadByte(); + this.objTargaHeader.ColorMap.Add(new Color32(r, g, b, 255)); + break; + case 32: + a = binReader.ReadByte(); + b = binReader.ReadByte(); + g = binReader.ReadByte(); + r = binReader.ReadByte(); + this.objTargaHeader.ColorMap.Add(new Color32(r, g, b, a)); + break; + default: + this.ClearAll(); + throw new Exception("TargaImage only supports ColorMap Entry Sizes of 15, 16, 24 or 32 bits."); + + } + + + } + } + catch (Exception ex) + { + this.ClearAll(); + throw ex; + } + + + + } + else + { + this.ClearAll(); + throw new Exception("Image Type requires a Color Map and Color Map Length is zero."); + } + } + + + } + else + { + if (this.objTargaHeader.ImageType == ImageType.UNCOMPRESSED_COLOR_MAPPED || + this.objTargaHeader.ImageType == ImageType.RUN_LENGTH_ENCODED_COLOR_MAPPED) + { + this.ClearAll(); + throw new Exception("Image Type requires a Color Map and there was not a Color Map included in the file."); + } + } + + + } + else + { + this.ClearAll(); + throw new Exception(@"Error loading file, could not read file from disk."); + } + } + + + /// + /// Loads the Targa Extension Area from the file, if it exists. + /// + /// A BinaryReader that points the loaded file byte stream. + private void LoadTGAExtensionArea(BinaryReader binReader) + { + + if (binReader != null && binReader.BaseStream != null && binReader.BaseStream.Length > 0 && binReader.BaseStream.CanSeek == true) + { + // is there an Extension Area in file + if (this.objTargaFooter.ExtensionAreaOffset > 0) + { + try + { + // set the cursor at the beginning of the Extension Area using ExtensionAreaOffset. + binReader.BaseStream.Seek(this.objTargaFooter.ExtensionAreaOffset, SeekOrigin.Begin); + + // load the extension area fields from the file + + this.objTargaExtensionArea.SetExtensionSize((int)(binReader.ReadInt16())); + this.objTargaExtensionArea.SetAuthorName(Encoding.ASCII.GetString(binReader.ReadBytes(TargaConstants.ExtensionAreaAuthorNameByteLength)).TrimEnd('\0')); + this.objTargaExtensionArea.SetAuthorComments(Encoding.ASCII.GetString(binReader.ReadBytes(TargaConstants.ExtensionAreaAuthorCommentsByteLength)).TrimEnd('\0')); + + + // get the date/time stamp of the file + Int16 iMonth = binReader.ReadInt16(); + Int16 iDay = binReader.ReadInt16(); + Int16 iYear = binReader.ReadInt16(); + Int16 iHour = binReader.ReadInt16(); + Int16 iMinute = binReader.ReadInt16(); + Int16 iSecond = binReader.ReadInt16(); + DateTime dtstamp; + string strStamp = iMonth.ToString() + @"/" + iDay.ToString() + @"/" + iYear.ToString() + @" "; + strStamp += iHour.ToString() + @":" + iMinute.ToString() + @":" + iSecond.ToString(); + if (DateTime.TryParse(strStamp, out dtstamp) == true) + this.objTargaExtensionArea.SetDateTimeStamp(dtstamp); + + + this.objTargaExtensionArea.SetJobName(Encoding.ASCII.GetString(binReader.ReadBytes(TargaConstants.ExtensionAreaJobNameByteLength)).TrimEnd('\0')); + + + // get the job time of the file + iHour = binReader.ReadInt16(); + iMinute = binReader.ReadInt16(); + iSecond = binReader.ReadInt16(); + TimeSpan ts = new TimeSpan((int)iHour, (int)iMinute, (int)iSecond); + this.objTargaExtensionArea.SetJobTime(ts); + + + this.objTargaExtensionArea.SetSoftwareID(Encoding.ASCII.GetString(binReader.ReadBytes(TargaConstants.ExtensionAreaSoftwareIDByteLength)).TrimEnd('\0')); + + + // get the version number and letter from file + float iVersionNumber = (float)binReader.ReadInt16() / 100.0F; + string strVersionLetter = Encoding.ASCII.GetString(binReader.ReadBytes(TargaConstants.ExtensionAreaSoftwareVersionLetterByteLength)).TrimEnd('\0'); + + + this.objTargaExtensionArea.SetSoftwareID(iVersionNumber.ToString(@"F2") + strVersionLetter); + + + // get the color key of the file + byte a = binReader.ReadByte(); + byte r = binReader.ReadByte(); + byte b = binReader.ReadByte(); + byte g = binReader.ReadByte(); + this.objTargaExtensionArea.SetKeyColor(new Color32(r, g, b, a)); + + + this.objTargaExtensionArea.SetPixelAspectRatioNumerator((int)binReader.ReadInt16()); + this.objTargaExtensionArea.SetPixelAspectRatioDenominator((int)binReader.ReadInt16()); + this.objTargaExtensionArea.SetGammaNumerator((int)binReader.ReadInt16()); + this.objTargaExtensionArea.SetGammaDenominator((int)binReader.ReadInt16()); + this.objTargaExtensionArea.SetColorCorrectionOffset(binReader.ReadInt32()); + this.objTargaExtensionArea.SetPostageStampOffset(binReader.ReadInt32()); + this.objTargaExtensionArea.SetScanLineOffset(binReader.ReadInt32()); + this.objTargaExtensionArea.SetAttributesType((int)binReader.ReadByte()); + + + // load Scan Line Table from file if any + if (this.objTargaExtensionArea.ScanLineOffset > 0) + { + binReader.BaseStream.Seek(this.objTargaExtensionArea.ScanLineOffset, SeekOrigin.Begin); + for (int i = 0; i < this.objTargaHeader.Height; i++) + { + this.objTargaExtensionArea.ScanLineTable.Add(binReader.ReadInt32()); + } + } + + + // load Color Correction Table from file if any + if (this.objTargaExtensionArea.ColorCorrectionOffset > 0) + { + binReader.BaseStream.Seek(this.objTargaExtensionArea.ColorCorrectionOffset, SeekOrigin.Begin); + for (int i = 0; i < TargaConstants.ExtensionAreaColorCorrectionTableValueLength; i++) + { + a = Convert.ToByte(binReader.ReadInt16()); + r = Convert.ToByte(binReader.ReadInt16()); + b = Convert.ToByte(binReader.ReadInt16()); + g = Convert.ToByte(binReader.ReadInt16()); + this.objTargaExtensionArea.ColorCorrectionTable.Add(new Color32(r, g, b, a)); + } + } + } + catch (Exception ex) + { + this.ClearAll(); + throw ex; + } + } + } + else + { + this.ClearAll(); + throw new Exception(@"Error loading file, could not read file from disk."); + } + } + + /// + /// Reads the image data bytes from the file. Handles Uncompressed and RLE Compressed image data. + /// Uses FirstPixelDestination to properly align the image. + /// + /// A BinaryReader that points the loaded file byte stream. + /// An array of bytes representing the image data in the proper alignment. + private byte[] LoadImageBytes(BinaryReader binReader) + { + + // read the image data into a byte array + // take into account stride has to be a multiple of 4 + // use padding to make sure multiple of 4 + + byte[] data = null; + if (binReader != null && binReader.BaseStream != null && binReader.BaseStream.Length > 0 && binReader.BaseStream.CanSeek == true) + { + if (this.objTargaHeader.ImageDataOffset > 0) + { + // padding bytes + byte[] padding = new byte[this.intPadding]; + MemoryStream msData = null; + + // seek to the beginning of the image data using the ImageDataOffset value + binReader.BaseStream.Seek(this.objTargaHeader.ImageDataOffset, SeekOrigin.Begin); + + + // get the size in bytes of each row in the image + int intImageRowByteSize = (int)this.objTargaHeader.Width * ((int)this.objTargaHeader.BytesPerPixel); + + // get the size in bytes of the whole image + int intImageByteSize = intImageRowByteSize * (int)this.objTargaHeader.Height; + + // is this a RLE compressed image type + if (this.objTargaHeader.ImageType == ImageType.RUN_LENGTH_ENCODED_BLACK_AND_WHITE || + this.objTargaHeader.ImageType == ImageType.RUN_LENGTH_ENCODED_COLOR_MAPPED || + this.objTargaHeader.ImageType == ImageType.RUN_LENGTH_ENCODED_TRUE_COLOR) + { + + #region COMPRESSED + + // RLE Packet info + byte bRLEPacket = 0; + int intRLEPacketType = -1; + int intRLEPixelCount = 0; + byte[] bRunLengthPixel = null; + + // used to keep track of bytes read + int intImageBytesRead = 0; + int intImageRowBytesRead = 0; + + // keep reading until we have the all image bytes + while (intImageBytesRead < intImageByteSize) + { + // get the RLE packet + bRLEPacket = binReader.ReadByte(); + intRLEPacketType = Utilities.GetBits(bRLEPacket, 7, 1); + intRLEPixelCount = Utilities.GetBits(bRLEPacket, 0, 7) + 1; + + // check the RLE packet type + if ((RLEPacketType)intRLEPacketType == RLEPacketType.RUN_LENGTH) + { + // get the pixel color data + bRunLengthPixel = binReader.ReadBytes((int)this.objTargaHeader.BytesPerPixel); + if (bRunLengthPixel.Length == 3) { //BGR -> RGB + var t = bRunLengthPixel [0]; + bRunLengthPixel [0] = bRunLengthPixel [2]; + bRunLengthPixel [2] = t; + } + + // add the number of pixels specified using the read pixel color + for (int i = 0; i < intRLEPixelCount; i++) + { + foreach (byte b in bRunLengthPixel) + row.Add(b); + + // increment the byte counts + intImageRowBytesRead += bRunLengthPixel.Length; + intImageBytesRead += bRunLengthPixel.Length; + + // if we have read a full image row + // add the row to the row list and clear it + // restart row byte count + if (intImageRowBytesRead == intImageRowByteSize) + { + rows.Add(row); + row = new List( row.Count ); + intImageRowBytesRead = 0; + } + } + + } + + else if ((RLEPacketType)intRLEPacketType == RLEPacketType.RAW) + { + // get the number of bytes to read based on the read pixel count + int intBytesToRead = intRLEPixelCount * this.objTargaHeader.BytesPerPixel; + + // read each byte + for (int i = 0;i < intBytesToRead;i++) + { + row.Add(binReader.ReadByte()); + if (this.objTargaHeader.BytesPerPixel == 3 && i % 3 == 2) { + var t = row[row.Count - 1]; + row[row.Count - 1] = row[row.Count - 3]; + row[row.Count - 3] = t; + } + // increment the byte counts + intImageBytesRead++; + intImageRowBytesRead++; + + // if we have read a full image row + // add the row to the row list and clear it + // restart row byte count + if (intImageRowBytesRead == intImageRowByteSize) + { + rows.Add(row); + row = new List( intImageRowByteSize ); + intImageRowBytesRead = 0; + } + + } + + } + } + + #endregion + + } + + else + { + #region NON-COMPRESSED + + // loop through each row in the image + for (int i = 0; i < (int)this.objTargaHeader.Height; i++) + { + // Read in the row + if (Header.BytesPerPixel == 3) { //bgr => rgb + var rowBytes = binReader.ReadBytes(intImageRowByteSize); + for (int j=0; j( row.Count ); + } + + + #endregion + } + + // flag that states whether or not to reverse the location of all rows. + bool blnRowsReverse = true; + + // flag that states whether or not to reverse the bytes in each row. + bool blnEachRowReverse = false; + + // Unity: We have the reverse behaviour due to in-memory texture alignment + // use FirstPixelDestination to determine the alignment of the + // image data byte + switch (this.objTargaHeader.FirstPixelDestination) + { + case FirstPixelDestination.TOP_LEFT: + blnRowsReverse = true; + blnEachRowReverse = true; + break; + + case FirstPixelDestination.TOP_RIGHT: + blnRowsReverse = true; + blnEachRowReverse = false; + break; + + case FirstPixelDestination.BOTTOM_LEFT: + blnRowsReverse = false; + blnEachRowReverse = true; + break; + + case FirstPixelDestination.BOTTOM_RIGHT: + case FirstPixelDestination.UNKNOWN: + blnRowsReverse = false; + blnEachRowReverse = false; + + break; + } + + // write the bytes from each row into a memory stream and get the + // resulting byte array + using (msData = new MemoryStream()) + { + + // do we reverse the rows in the row list. + if (blnRowsReverse == true) + rows.Reverse(); + + // go through each row + for (int i = 0; i < rows.Count; i++) + { + // do we reverse the bytes in the row + if (blnEachRowReverse == true) + rows[i].Reverse(); + + // get the byte array for the row + byte[] brow = rows[i].ToArray(); + + // write the row bytes and padding bytes to the memory streem + msData.Write(brow, 0, brow.Length); + //msData.Write(padding, 0, padding.Length); //经测试不需要输出padding,否则24位TargaImage会显示异常 + } + // get the image byte array + data = msData.ToArray(); + + + + } + + } + else + { + this.ClearAll(); + throw new Exception(@"Error loading file, No image data in file."); + } + } + else + { + this.ClearAll(); + throw new Exception(@"Error loading file, could not read file from disk."); + } + + // return the image byte array + return data; + + } + + /// + /// Reads the image data bytes from the file and loads them into the Image Bitmap object. + /// Also loads the color map, if any, into the Image Bitmap. + /// + /// A BinaryReader that points the loaded file byte stream. + private void LoadTGAImage(BinaryReader binReader) + { + //************** NOTE ******************* + // The memory allocated for Microsoft Bitmaps must be aligned on a 32bit boundary. + // The stride refers to the number of bytes allocated for one scanline of the bitmap. + // In your loop, you copy the pixels one scanline at a time and take into + // consideration the amount of padding that occurs due to memory alignment. + // calculate the stride, in bytes, of the image (32bit aligned width of each image row) + this.intStride = (((int)this.objTargaHeader.Width * (int)this.objTargaHeader.PixelDepth + 31) & ~31) >> 3; // width in bytes + + // calculate the padding, in bytes, of the image + // number of bytes to add to make each row a 32bit aligned row + // padding in bytes + this.intPadding = this.intStride - ((((int)this.objTargaHeader.Width * (int)this.objTargaHeader.PixelDepth) + 7) / 8); + + // get the image data bytes + byte[] bimagedata = this.LoadImageBytes(binReader); + + // get the Pixel format to use with the Bitmap object + TextureFormat pf = this.GetPixelFormat(); + + + + + if (pf == TextureFormat.BGRA32) { + bmpTargaImage = new Texture2D((int)this.objTargaHeader.Width, (int)this.objTargaHeader.Height); + bmpTargaImage.SetPixels (Utils.Bgra32ToColors(bimagedata)); + } else { + bmpTargaImage = new Texture2D((int)this.objTargaHeader.Width, (int)this.objTargaHeader.Height, pf, false); + bmpTargaImage.LoadRawTextureData (bimagedata); + } + bmpTargaImage.Apply(); + + this.LoadThumbnail(binReader, pf); + + // Unity: Ripped out a bunch of palette code + } + + /// + /// Gets the PixelFormat to be used by the Image based on the Targa file's attributes + /// + /// + /// Unity: We probably can't support most of these, so I just changed them to a best guess. + /// + /// + private TextureFormat GetPixelFormat() + { + TextureFormat targaPixelFormat = TextureFormat.ARGB32; + + // first off what is our Pixel Depth (bits per pixel) + switch (this.objTargaHeader.PixelDepth) + { + case 8: + targaPixelFormat = TextureFormat.Alpha8; + break; + + case 16: + if (this.Format == TGAFormat.NEW_TGA) + { + switch (this.objTargaExtensionArea.AttributesType) + { + case 0: + case 1: + case 2: // no alpha data + targaPixelFormat = TextureFormat.RGB565; + break; + + case 3: // useful alpha data + targaPixelFormat = TextureFormat.RGB565; + break; + } + } + else + { + targaPixelFormat = TextureFormat.RGB565; + } + + break; + + case 24: + targaPixelFormat = TextureFormat.RGB24; + break; + + case 32: + if (this.Format == TGAFormat.NEW_TGA) + { + switch (this.objTargaExtensionArea.AttributesType) + { + + case 1: + case 2: // no alpha data + targaPixelFormat = TextureFormat.BGRA32; + break; + + case 0: + case 3: // useful alpha data + targaPixelFormat = TextureFormat.BGRA32; + break; + + case 4: // premultiplied alpha data + targaPixelFormat = TextureFormat.BGRA32; + break; + + } + } + else + { + targaPixelFormat = TextureFormat.BGRA32; + break; + } + break; + } + + return targaPixelFormat; + } + + + /// + /// Loads the thumbnail of the loaded image file, if any. + /// + /// A BinaryReader that points the loaded file byte stream. + /// A PixelFormat value indicating what pixel format to use when loading the thumbnail. + private void LoadThumbnail(BinaryReader binReader, TextureFormat pfPixelFormat) + { + + // read the Thumbnail image data into a byte array + // take into account stride has to be a multiple of 4 + // use padding to make sure multiple of 4 + + byte[] data = null; + if (binReader != null && binReader.BaseStream != null && binReader.BaseStream.Length > 0 && binReader.BaseStream.CanSeek == true) + { + if (this.ExtensionArea.PostageStampOffset > 0) + { + + // seek to the beginning of the image data using the ImageDataOffset value + binReader.BaseStream.Seek(this.ExtensionArea.PostageStampOffset, SeekOrigin.Begin); + + int iWidth = (int)binReader.ReadByte(); + int iHeight = (int)binReader.ReadByte(); + + int iStride = ((iWidth * (int)this.objTargaHeader.PixelDepth + 31) & ~31) >> 3; // width in bytes + int iPadding = iStride - (((iWidth * (int)this.objTargaHeader.PixelDepth) + 7) / 8); + + List> objRows = new List>(); + List objRow = new List(); + + + + + byte[] padding = new byte[iPadding]; + MemoryStream msData = null; + bool blnEachRowReverse = false; + bool blnRowsReverse = false; + + + using (msData = new MemoryStream()) + { + // get the size in bytes of each row in the image + int intImageRowByteSize = iWidth * ((int)this.objTargaHeader.PixelDepth / 8); + + // thumbnails are never compressed + for (int i = 0; i < iHeight; i++) + { + objRow.AddRange( binReader.ReadBytes(intImageRowByteSize) ); + objRows.Add(objRow); + objRow = new List( intImageRowByteSize ); + } + + switch (this.objTargaHeader.FirstPixelDestination) + { + case FirstPixelDestination.TOP_LEFT: + break; + + case FirstPixelDestination.TOP_RIGHT: + blnRowsReverse = false; + blnEachRowReverse = false; + break; + + case FirstPixelDestination.BOTTOM_LEFT: + break; + + case FirstPixelDestination.BOTTOM_RIGHT: + case FirstPixelDestination.UNKNOWN: + blnRowsReverse = true; + blnEachRowReverse = false; + + break; + } + + if (blnRowsReverse == true) + objRows.Reverse(); + + for (int i = 0; i < objRows.Count; i++) + { + if (blnEachRowReverse == true) + objRows[i].Reverse(); + + byte[] brow = objRows[i].ToArray(); + msData.Write(brow, 0, brow.Length); + msData.Write(padding, 0, padding.Length); + } + data = msData.ToArray(); + } + + if (data != null && data.Length > 0) + { + // Unity: use Texture2D + bmpImageThumbnail = new Texture2D( iWidth, iHeight, pfPixelFormat, false); + bmpImageThumbnail.LoadRawTextureData( data ); + } + } + else + { + +#if UNITY_EDITOR + GameObject.DestroyImmediate(bmpImageThumbnail); +#else + Object.Destroy( bmpImageThumbnail ); +#endif + + bmpImageThumbnail = null; + } + } + else + { + +#if UNITY_EDITOR + GameObject.DestroyImmediate(bmpImageThumbnail); +#else + GameObject.Destroy(bmpImageThumbnail); +#endif + + bmpImageThumbnail = null; + } + + } + + /// + /// Clears out all objects and resources. + /// + private void ClearAll() + { +#if UNITY_EDITOR + GameObject.DestroyImmediate(bmpTargaImage); + GameObject.DestroyImmediate(bmpImageThumbnail); +#else + Object.Destroy( bmpTargaImage ); + Object.Destroy( bmpImageThumbnail ); +#endif + + this.bmpTargaImage = null; + this.bmpImageThumbnail = null; + + this.objTargaHeader = new TargaHeader(); + this.objTargaExtensionArea = new TargaExtensionArea(); + this.objTargaFooter = new TargaFooter(); + this.eTGAFormat = TGAFormat.UNKNOWN; + this.intStride = 0; + this.intPadding = 0; + this.rows.Clear(); + this.row.Clear(); + this.strFileName = string.Empty; + + } + + /// + /// Loads a Targa image file into a Bitmap object. + /// + /// The Targa image filename + /// A Bitmap object with the Targa image loaded into it. + public static Texture2D LoadTargaImage(string sFileName) + { + TargaImage ti = new TargaImage(sFileName); + return ti.bmpTargaImage; + } + } + + + /// + /// This class holds all of the header properties of a Targa image. + /// This includes the TGA File Header section the ImageID and the Color Map. + /// + public class TargaHeader + { + private byte bImageIDLength = 0; + private ColorMapType eColorMapType = ColorMapType.NO_COLOR_MAP; + private ImageType eImageType = ImageType.NO_IMAGE_DATA; + private short sColorMapFirstEntryIndex = 0; + private short sColorMapLength = 0; + private byte bColorMapEntrySize = 0; + private short sXOrigin = 0; + private short sYOrigin = 0; + private short sWidth = 0; + private short sHeight = 0; + private byte bPixelDepth = 0; + private byte bImageDescriptor = 0; + private VerticalTransferOrder eVerticalTransferOrder = VerticalTransferOrder.UNKNOWN; + private HorizontalTransferOrder eHorizontalTransferOrder = HorizontalTransferOrder.UNKNOWN; + private byte bAttributeBits = 0; + private string strImageIDValue = string.Empty; + private List cColorMap = new List(); + + /// + /// Gets the number of bytes contained the ImageIDValue property. The maximum + /// number of characters is 255. A value of zero indicates that no ImageIDValue is included with the + /// image. + /// + public byte ImageIDLength + { + get { return this.bImageIDLength; } + } + + /// + /// Sets the ImageIDLength property, available only to objects in the same assembly as TargaHeader. + /// + /// The Image ID Length value read from the file. + internal protected void SetImageIDLength(byte bImageIDLength) + { + this.bImageIDLength = bImageIDLength; + } + + /// + /// Gets the type of color map (if any) included with the image. There are currently 2 + /// defined values for this field: + /// NO_COLOR_MAP - indicates that no color-map data is included with this image. + /// COLOR_MAP_INCLUDED - indicates that a color-map is included with this image. + /// + public ColorMapType ColorMapType + { + get { return this.eColorMapType; } + } + + /// + /// Sets the ColorMapType property, available only to objects in the same assembly as TargaHeader. + /// + /// One of the ColorMapType enumeration values. + internal protected void SetColorMapType(ColorMapType eColorMapType) + { + this.eColorMapType = eColorMapType; + } + + /// + /// Gets one of the ImageType enumeration values indicating the type of Targa image read from the file. + /// + public ImageType ImageType + { + get { return this.eImageType; } + } + + /// + /// Sets the ImageType property, available only to objects in the same assembly as TargaHeader. + /// + /// One of the ImageType enumeration values. + internal protected void SetImageType(ImageType eImageType) + { + this.eImageType = eImageType; + } + + /// + /// Gets the index of the first color map entry. ColorMapFirstEntryIndex refers to the starting entry in loading the color map. + /// + public short ColorMapFirstEntryIndex + { + get { return this.sColorMapFirstEntryIndex; } + } + + /// + /// Sets the ColorMapFirstEntryIndex property, available only to objects in the same assembly as TargaHeader. + /// + /// The First Entry Index value read from the file. + internal protected void SetColorMapFirstEntryIndex(short sColorMapFirstEntryIndex) + { + this.sColorMapFirstEntryIndex = sColorMapFirstEntryIndex; + } + + /// + /// Gets total number of color map entries included. + /// + public short ColorMapLength + { + get { return this.sColorMapLength; } + } + + /// + /// Sets the ColorMapLength property, available only to objects in the same assembly as TargaHeader. + /// + /// The Color Map Length value read from the file. + internal protected void SetColorMapLength(short sColorMapLength) + { + this.sColorMapLength = sColorMapLength; + } + + /// + /// Gets the number of bits per entry in the Color Map. Typically 15, 16, 24 or 32-bit values are used. + /// + public byte ColorMapEntrySize + { + get { return this.bColorMapEntrySize; } + } + + /// + /// Sets the ColorMapEntrySize property, available only to objects in the same assembly as TargaHeader. + /// + /// The Color Map Entry Size value read from the file. + internal protected void SetColorMapEntrySize(byte bColorMapEntrySize) + { + this.bColorMapEntrySize = bColorMapEntrySize; + } + + /// + /// Gets the absolute horizontal coordinate for the lower + /// left corner of the image as it is positioned on a display device having + /// an origin at the lower left of the screen (e.g., the TARGA series). + /// + public short XOrigin + { + get { return this.sXOrigin; } + } + + /// + /// Sets the XOrigin property, available only to objects in the same assembly as TargaHeader. + /// + /// The X Origin value read from the file. + internal protected void SetXOrigin(short sXOrigin) + { + this.sXOrigin = sXOrigin; + } + + /// + /// These bytes specify the absolute vertical coordinate for the lower left + /// corner of the image as it is positioned on a display device having an + /// origin at the lower left of the screen (e.g., the TARGA series). + /// + public short YOrigin + { + get { return this.sYOrigin; } + } + + /// + /// Sets the YOrigin property, available only to objects in the same assembly as TargaHeader. + /// + /// The Y Origin value read from the file. + internal protected void SetYOrigin(short sYOrigin) + { + this.sYOrigin = sYOrigin; + } + + /// + /// Gets the width of the image in pixels. + /// + public short Width + { + get { return this.sWidth; } + } + + /// + /// Sets the Width property, available only to objects in the same assembly as TargaHeader. + /// + /// The Width value read from the file. + internal protected void SetWidth(short sWidth) + { + this.sWidth = sWidth; + } + + /// + /// Gets the height of the image in pixels. + /// + public short Height + { + get { return this.sHeight; } + } + + /// + /// Sets the Height property, available only to objects in the same assembly as TargaHeader. + /// + /// The Height value read from the file. + internal protected void SetHeight(short sHeight) + { + this.sHeight = sHeight; + } + + /// + /// Gets the number of bits per pixel. This number includes + /// the Attribute or Alpha channel bits. Common values are 8, 16, 24 and 32. + /// + public byte PixelDepth + { + get { return this.bPixelDepth; } + } + + /// + /// Sets the PixelDepth property, available only to objects in the same assembly as TargaHeader. + /// + /// The Pixel Depth value read from the file. + internal protected void SetPixelDepth(byte bPixelDepth) + { + this.bPixelDepth = bPixelDepth; + } + + /// + /// Gets or Sets the ImageDescriptor property. The ImageDescriptor is the byte that holds the + /// Image Origin and Attribute Bits values. + /// Available only to objects in the same assembly as TargaHeader. + /// + internal protected byte ImageDescriptor + { + get { return this.bImageDescriptor; } + set { this.bImageDescriptor = value; } + } + + /// + /// Gets one of the FirstPixelDestination enumeration values specifying the screen destination of first pixel based on VerticalTransferOrder and HorizontalTransferOrder + /// + public FirstPixelDestination FirstPixelDestination + { + get + { + + if (this.eVerticalTransferOrder == VerticalTransferOrder.UNKNOWN || this.eHorizontalTransferOrder == HorizontalTransferOrder.UNKNOWN) + return FirstPixelDestination.UNKNOWN; + else if (this.eVerticalTransferOrder == VerticalTransferOrder.BOTTOM && this.eHorizontalTransferOrder == HorizontalTransferOrder.LEFT) + return FirstPixelDestination.BOTTOM_LEFT; + else if (this.eVerticalTransferOrder == VerticalTransferOrder.BOTTOM && this.eHorizontalTransferOrder == HorizontalTransferOrder.RIGHT) + return FirstPixelDestination.BOTTOM_RIGHT; + else if (this.eVerticalTransferOrder == VerticalTransferOrder.TOP && this.eHorizontalTransferOrder == HorizontalTransferOrder.LEFT) + return FirstPixelDestination.TOP_LEFT; + else + return FirstPixelDestination.TOP_RIGHT; + + } + } + + + /// + /// Gets one of the VerticalTransferOrder enumeration values specifying the top-to-bottom ordering in which pixel data is transferred from the file to the screen. + /// + public VerticalTransferOrder VerticalTransferOrder + { + get { return this.eVerticalTransferOrder; } + } + + /// + /// Sets the VerticalTransferOrder property, available only to objects in the same assembly as TargaHeader. + /// + /// One of the VerticalTransferOrder enumeration values. + internal protected void SetVerticalTransferOrder(VerticalTransferOrder eVerticalTransferOrder) + { + this.eVerticalTransferOrder = eVerticalTransferOrder; + } + + /// + /// Gets one of the HorizontalTransferOrder enumeration values specifying the left-to-right ordering in which pixel data is transferred from the file to the screen. + /// + public HorizontalTransferOrder HorizontalTransferOrder + { + get { return this.eHorizontalTransferOrder; } + } + + /// + /// Sets the HorizontalTransferOrder property, available only to objects in the same assembly as TargaHeader. + /// + /// One of the HorizontalTransferOrder enumeration values. + internal protected void SetHorizontalTransferOrder(HorizontalTransferOrder eHorizontalTransferOrder) + { + this.eHorizontalTransferOrder = eHorizontalTransferOrder; + } + + /// + /// Gets the number of attribute bits per pixel. + /// + public byte AttributeBits + { + get { return this.bAttributeBits; } + } + + /// + /// Sets the AttributeBits property, available only to objects in the same assembly as TargaHeader. + /// + /// The Attribute Bits value read from the file. + internal protected void SetAttributeBits(byte bAttributeBits) + { + this.bAttributeBits = bAttributeBits; + } + + /// + /// Gets identifying information about the image. + /// A value of zero in ImageIDLength indicates that no ImageIDValue is included with the image. + /// + public string ImageIDValue + { + get { return this.strImageIDValue; } + } + + /// + /// Sets the ImageIDValue property, available only to objects in the same assembly as TargaHeader. + /// + /// The Image ID value read from the file. + internal protected void SetImageIDValue(string strImageIDValue) + { + this.strImageIDValue = strImageIDValue; + } + + /// + /// Gets the Color Map of the image, if any. The Color Map is represented by a list of Color objects. + /// + public List ColorMap + { + get { return this.cColorMap; } + } + + /// + /// Gets the offset from the beginning of the file to the Image Data. + /// + public int ImageDataOffset + { + get + { + // calculate the image data offset + + // start off with the number of bytes holding the header info. + int intImageDataOffset = TargaConstants.HeaderByteLength; + + // add the Image ID length (could be variable) + intImageDataOffset += this.bImageIDLength; + + // determine the number of bytes for each Color Map entry + int Bytes = 0; + switch (this.bColorMapEntrySize) + { + case 15: + Bytes = 2; + break; + case 16: + Bytes = 2; + break; + case 24: + Bytes = 3; + break; + case 32: + Bytes = 4; + break; + } + + // add the length of the color map + intImageDataOffset += ((int)this.sColorMapLength * (int)Bytes); + + // return result + return intImageDataOffset; + } + } + + /// + /// Gets the number of bytes per pixel. + /// + public int BytesPerPixel + { + get + { + return (int)this.bPixelDepth / 8; + } + } + } + + + /// + /// Holds Footer infomation read from the image file. + /// + public class TargaFooter + { + private int intExtensionAreaOffset = 0; + private int intDeveloperDirectoryOffset = 0; + private string strSignature = string.Empty; + private string strReservedCharacter = string.Empty; + + /// + /// Gets the offset from the beginning of the file to the start of the Extension Area. + /// If the ExtensionAreaOffset is zero, no Extension Area exists in the file. + /// + public int ExtensionAreaOffset + { + get { return this.intExtensionAreaOffset; } + } + + /// + /// Sets the ExtensionAreaOffset property, available only to objects in the same assembly as TargaFooter. + /// + /// The Extension Area Offset value read from the file. + internal protected void SetExtensionAreaOffset(int intExtensionAreaOffset) + { + this.intExtensionAreaOffset = intExtensionAreaOffset; + } + + /// + /// Gets the offset from the beginning of the file to the start of the Developer Area. + /// If the DeveloperDirectoryOffset is zero, then the Developer Area does not exist + /// + public int DeveloperDirectoryOffset + { + get { return this.intDeveloperDirectoryOffset; } + } + + /// + /// Sets the DeveloperDirectoryOffset property, available only to objects in the same assembly as TargaFooter. + /// + /// The Developer Directory Offset value read from the file. + internal protected void SetDeveloperDirectoryOffset(int intDeveloperDirectoryOffset) + { + this.intDeveloperDirectoryOffset = intDeveloperDirectoryOffset; + } + + /// + /// This string is formatted exactly as "TRUEVISION-XFILE" (no quotes). If the + /// signature is detected, the file is assumed to be a New TGA format and MAY, + /// therefore, contain the Developer Area and/or the Extension Areas. If the + /// signature is not found, then the file is assumed to be an Original TGA format. + /// + public string Signature + { + get { return this.strSignature; } + } + + /// + /// Sets the Signature property, available only to objects in the same assembly as TargaFooter. + /// + /// The Signature value read from the file. + internal protected void SetSignature(string strSignature) + { + this.strSignature = strSignature; + } + + /// + /// A New Targa format reserved character "." (period) + /// + public string ReservedCharacter + { + get { return this.strReservedCharacter; } + } + + /// + /// Sets the ReservedCharacter property, available only to objects in the same assembly as TargaFooter. + /// + /// The ReservedCharacter value read from the file. + internal protected void SetReservedCharacter(string strReservedCharacter) + { + this.strReservedCharacter = strReservedCharacter; + } + + /// + /// Creates a new instance of the TargaFooter class. + /// + public TargaFooter() + {} + + + } + + + /// + /// This class holds all of the Extension Area properties of the Targa image. If an Extension Area exists in the file. + /// + public class TargaExtensionArea + { + int intExtensionSize = 0; + string strAuthorName = string.Empty; + string strAuthorComments = string.Empty; + DateTime dtDateTimeStamp = DateTime.Now; + string strJobName = string.Empty; + TimeSpan dtJobTime = TimeSpan.Zero; + string strSoftwareID = string.Empty; + string strSoftwareVersion = string.Empty; + Color cKeyColor; + int intPixelAspectRatioNumerator = 0; + int intPixelAspectRatioDenominator = 0; + int intGammaNumerator = 0; + int intGammaDenominator = 0; + int intColorCorrectionOffset = 0; + int intPostageStampOffset = 0; + int intScanLineOffset = 0; + int intAttributesType = 0; + private List intScanLineTable = new List(); + private List cColorCorrectionTable = new List(); + + /// + /// Gets the number of Bytes in the fixed-length portion of the ExtensionArea. + /// For Version 2.0 of the TGA File Format, this number should be set to 495 + /// + public int ExtensionSize + { + get { return this.intExtensionSize; } + } + + /// + /// Sets the ExtensionSize property, available only to objects in the same assembly as TargaExtensionArea. + /// + /// The Extension Size value read from the file. + internal protected void SetExtensionSize(int intExtensionSize) + { + this.intExtensionSize = intExtensionSize; + } + + /// + /// Gets the name of the person who created the image. + /// + public string AuthorName + { + get { return this.strAuthorName; } + } + + /// + /// Sets the AuthorName property, available only to objects in the same assembly as TargaExtensionArea. + /// + /// The Author Name value read from the file. + internal protected void SetAuthorName(string strAuthorName) + { + this.strAuthorName = strAuthorName; + } + + /// + /// Gets the comments from the author who created the image. + /// + public string AuthorComments + { + get { return this.strAuthorComments; } + } + + /// + /// Sets the AuthorComments property, available only to objects in the same assembly as TargaExtensionArea. + /// + /// The Author Comments value read from the file. + internal protected void SetAuthorComments(string strAuthorComments) + { + this.strAuthorComments = strAuthorComments; + } + + /// + /// Gets the date and time that the image was saved. + /// + public DateTime DateTimeStamp + { + get { return this.dtDateTimeStamp; } + } + + /// + /// Sets the DateTimeStamp property, available only to objects in the same assembly as TargaExtensionArea. + /// + /// The Date Time Stamp value read from the file. + internal protected void SetDateTimeStamp(DateTime dtDateTimeStamp) + { + this.dtDateTimeStamp = dtDateTimeStamp; + } + + /// + /// Gets the name or id tag which refers to the job with which the image was associated. + /// + public string JobName + { + get { return this.strJobName; } + } + + /// + /// Sets the JobName property, available only to objects in the same assembly as TargaExtensionArea. + /// + /// The Job Name value read from the file. + internal protected void SetJobName(string strJobName) + { + this.strJobName = strJobName; + } + + /// + /// Gets the job elapsed time when the image was saved. + /// + public TimeSpan JobTime + { + get { return this.dtJobTime; } + } + + /// + /// Sets the JobTime property, available only to objects in the same assembly as TargaExtensionArea. + /// + /// The Job Time value read from the file. + internal protected void SetJobTime(TimeSpan dtJobTime) + { + this.dtJobTime = dtJobTime; + } + + /// + /// Gets the Software ID. Usually used to determine and record with what program a particular image was created. + /// + public string SoftwareID + { + get { return this.strSoftwareID; } + } + + /// + /// Sets the SoftwareID property, available only to objects in the same assembly as TargaExtensionArea. + /// + /// The Software ID value read from the file. + internal protected void SetSoftwareID(string strSoftwareID) + { + this.strSoftwareID = strSoftwareID; + } + + /// + /// Gets the version of software defined by the SoftwareID. + /// + public string SoftwareVersion + { + get { return this.strSoftwareVersion; } + } + + /// + /// Sets the SoftwareVersion property, available only to objects in the same assembly as TargaExtensionArea. + /// + /// The Software Version value read from the file. + internal protected void SetSoftwareVersion(string strSoftwareVersion) + { + this.strSoftwareVersion = strSoftwareVersion; + } + + /// + /// Gets the key color in effect at the time the image is saved. + /// The Key Color can be thought of as the "background color" or "transparent color". + /// + public Color KeyColor + { + get { return this.cKeyColor; } + } + + /// + /// Sets the KeyColor property, available only to objects in the same assembly as TargaExtensionArea. + /// + /// The Key Color value read from the file. + internal protected void SetKeyColor(Color cKeyColor) + { + this.cKeyColor = cKeyColor; + } + + /// + /// Gets the Pixel Ratio Numerator. + /// + public int PixelAspectRatioNumerator + { + get { return this.intPixelAspectRatioNumerator; } + } + + /// + /// Sets the PixelAspectRatioNumerator property, available only to objects in the same assembly as TargaExtensionArea. + /// + /// The Pixel Aspect Ratio Numerator value read from the file. + internal protected void SetPixelAspectRatioNumerator(int intPixelAspectRatioNumerator) + { + this.intPixelAspectRatioNumerator = intPixelAspectRatioNumerator; + } + + /// + /// Gets the Pixel Ratio Denominator. + /// + public int PixelAspectRatioDenominator + { + get { return this.intPixelAspectRatioDenominator; } + } + + /// + /// Sets the PixelAspectRatioDenominator property, available only to objects in the same assembly as TargaExtensionArea. + /// + /// The Pixel Aspect Ratio Denominator value read from the file. + internal protected void SetPixelAspectRatioDenominator(int intPixelAspectRatioDenominator) + { + this.intPixelAspectRatioDenominator = intPixelAspectRatioDenominator; + } + + /// + /// Gets the Pixel Aspect Ratio. + /// + public float PixelAspectRatio + { + get + { + if (this.intPixelAspectRatioDenominator > 0) + { + return (float)this.intPixelAspectRatioNumerator / (float)this.intPixelAspectRatioDenominator; + } + else + return 0.0F; + } + } + + /// + /// Gets the Gamma Numerator. + /// + public int GammaNumerator + { + get { return this.intGammaNumerator; } + } + + /// + /// Sets the GammaNumerator property, available only to objects in the same assembly as TargaExtensionArea. + /// + /// The Gamma Numerator value read from the file. + internal protected void SetGammaNumerator(int intGammaNumerator) + { + this.intGammaNumerator = intGammaNumerator; + } + + /// + /// Gets the Gamma Denominator. + /// + public int GammaDenominator + { + get { return this.intGammaDenominator; } + } + + /// + /// Sets the GammaDenominator property, available only to objects in the same assembly as TargaExtensionArea. + /// + /// The Gamma Denominator value read from the file. + internal protected void SetGammaDenominator(int intGammaDenominator) + { + this.intGammaDenominator = intGammaDenominator; + } + + /// + /// Gets the Gamma Ratio. + /// + public float GammaRatio + { + get + { + if (this.intGammaDenominator > 0) + { + float ratio = (float)this.intGammaNumerator / (float)this.intGammaDenominator; + return (float)Math.Round(ratio, 1); + } + else + return 1.0F; + } + } + + /// + /// Gets the offset from the beginning of the file to the start of the Color Correction table. + /// + public int ColorCorrectionOffset + { + get { return this.intColorCorrectionOffset; } + } + + /// + /// Sets the ColorCorrectionOffset property, available only to objects in the same assembly as TargaExtensionArea. + /// + /// The Color Correction Offset value read from the file. + internal protected void SetColorCorrectionOffset(int intColorCorrectionOffset) + { + this.intColorCorrectionOffset = intColorCorrectionOffset; + } + + /// + /// Gets the offset from the beginning of the file to the start of the Postage Stamp image data. + /// + public int PostageStampOffset + { + get { return this.intPostageStampOffset; } + } + + /// + /// Sets the PostageStampOffset property, available only to objects in the same assembly as TargaExtensionArea. + /// + /// The Postage Stamp Offset value read from the file. + internal protected void SetPostageStampOffset(int intPostageStampOffset) + { + this.intPostageStampOffset = intPostageStampOffset; + } + + /// + /// Gets the offset from the beginning of the file to the start of the Scan Line table. + /// + public int ScanLineOffset + { + get { return this.intScanLineOffset; } + } + + /// + /// Sets the ScanLineOffset property, available only to objects in the same assembly as TargaExtensionArea. + /// + /// The Scan Line Offset value read from the file. + internal protected void SetScanLineOffset(int intScanLineOffset) + { + this.intScanLineOffset = intScanLineOffset; + } + + /// + /// Gets the type of Alpha channel data contained in the file. + /// 0: No Alpha data included. + /// 1: Undefined data in the Alpha field, can be ignored + /// 2: Undefined data in the Alpha field, but should be retained + /// 3: Useful Alpha channel data is present + /// 4: Pre-multiplied Alpha (see description below) + /// 5-127: RESERVED + /// 128-255: Un-assigned + /// + public int AttributesType + { + get { return this.intAttributesType; } + } + + /// + /// Sets the AttributesType property, available only to objects in the same assembly as TargaExtensionArea. + /// + /// The Attributes Type value read from the file. + internal protected void SetAttributesType(int intAttributesType) + { + this.intAttributesType = intAttributesType; + } + + /// + /// Gets a list of offsets from the beginning of the file that point to the start of the next scan line, + /// in the order that the image was saved + /// + public List ScanLineTable + { + get { return this.intScanLineTable; } + } + + /// + /// Gets a list of Colors where each Color value is the desired Color correction for that entry. + /// This allows the user to store a correction table for image remapping or LUT driving. + /// + public List ColorCorrectionTable + { + get { return this.cColorCorrectionTable; } + } + + } + + + /// + /// Utilities functions used by the TargaImage class. + /// + static class Utilities + { + + /// + /// Gets an int value representing the subset of bits from a single Byte. + /// + /// The Byte used to get the subset of bits from. + /// The offset of bits starting from the right. + /// The number of bits to read. + /// + /// An int value representing the subset of bits. + /// + /// + /// Given -> b = 00110101 + /// A call to GetBits(b, 2, 4) + /// GetBits looks at the following bits in the byte -> 00{1101}00 + /// Returns 1101 as an int (13) + /// + internal static int GetBits(byte b, int offset, int count) + { + return (b >> offset) & ((1 << count) - 1); + } + + /// + /// Reads ARGB values from the 16 bits of two given Bytes in a 1555 format. + /// + /// The first Byte. + /// The Second Byte. + /// A Color with a ARGB values read from the two given Bytes + /// + /// Gets the ARGB values from the 16 bits in the two bytes based on the below diagram + /// | BYTE 1 | BYTE 2 | + /// | A RRRRR GG | GGG BBBBB | + /// + internal static Color GetColorFrom2Bytes(byte one, byte two) + { + // get the 5 bits used for the RED value from the first byte + int r1 = GetBits(one, 2, 5); + byte r = Convert.ToByte(r1 << 3); + + // get the two high order bits for GREEN from the from the first byte + int bit = GetBits(one, 0, 2); + // shift bits to the high order + int g1 = bit << 6; + + // get the 3 low order bits for GREEN from the from the second byte + bit = GetBits(two, 5, 3); + // shift the low order bits + int g2 = bit << 3; + // add the shifted values together to get the full GREEN value + byte g = Convert.ToByte(g1 + g2); + + // get the 5 bits used for the BLUE value from the second byte + int b1 = GetBits(two, 0, 5); + byte b = Convert.ToByte(b1 << 3); + + // get the 1 bit used for the ALPHA value from the first byte + int a1 = GetBits(one, 7, 1); + byte a = Convert.ToByte(a1 * 255); + + // return the resulting Color + return new Color32(r, g, b, a); + } + + /// + /// Gets a 32 character binary string of the specified Int32 value. + /// + /// The value to get a binary string for. + /// A string with the resulting binary for the supplied value. + /// + /// This method was used during debugging and is left here just for fun. + /// + internal static string GetIntBinaryString(Int32 n) + { + char[] b = new char[32]; + int pos = 31; + int i = 0; + + while (i < 32) + { + if ((n & (1 << i)) != 0) + { + b[pos] = '1'; + } + else + { + b[pos] = '0'; + } + pos--; + i++; + } + return new string(b); + } + + /// + /// Gets a 16 character binary string of the specified Int16 value. + /// + /// The value to get a binary string for. + /// A string with the resulting binary for the supplied value. + /// + /// This method was used during debugging and is left here just for fun. + /// + internal static string GetInt16BinaryString(Int16 n) + { + char[] b = new char[16]; + int pos = 15; + int i = 0; + + while (i < 16) + { + if ((n & (1 << i)) != 0) + { + b[pos] = '1'; + } + else + { + b[pos] = '0'; + } + pos--; + i++; + } + return new string(b); + } + + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/TargaImage.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/TargaImage.cs.meta new file mode 100644 index 0000000..10a6fe8 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/TargaImage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c3917c9113eb16f4a804239cdcbeade2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/TextureImage.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/TextureImage.cs new file mode 100644 index 0000000..68f6b9c --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/TextureImage.cs @@ -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; + } + } +} + diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/TextureImage.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/TextureImage.cs.meta new file mode 100644 index 0000000..ac0f631 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ImageLoader/TextureImage.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d15bd2e8f26ad1d49a28da77c1ae253d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MMDModel.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MMDModel.cs new file mode 100644 index 0000000..514f0bb --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MMDModel.cs @@ -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 Unity_MMDBoneNameDictionary = new Dictionary() + { + {"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 Alt_OriginalNameDictionary = new Dictionary() + { + {"右足先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 MaterialMorphNames { get; private set; } = new List(); + + public Dictionary OriginalBone_IndexDictionary { get; private set; } + = new Dictionary(); + public Dictionary Alt_OriginalBoneDictionary { get; private set; } + = new Dictionary(); + + + 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 ImportModel(string filePath, bool autoShowModel = true) + { + GameObject modelObject = new GameObject(); + MMDModel mmdModel = modelObject.AddComponent(); + await mmdModel.LoadModel(filePath); + if (autoShowModel) { mmdModel.ShowModel(); } + return mmdModel; + } + + async Task 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.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> colliderGroups = new Dictionary>(); + 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()); + } + + 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(); + colliderGroups[mmdRigidBody.CollisionGroup].Add(boxCollider); + boxCollider.size = mmdRigidBody.Dimemsions; + break; + case MMDRigidBody.RigidBodyShape.RigidShapeCapsule: + CapsuleCollider capsuleCollider = colliderObject.AddComponent(); + colliderGroups[mmdRigidBody.CollisionGroup].Add(capsuleCollider); + capsuleCollider.radius = mmdRigidBody.Dimemsions.x; + capsuleCollider.height = mmdRigidBody.Dimemsions.y; + break; + case MMDRigidBody.RigidBodyShape.RigidShapeSphere: + SphereCollider sphereCollider = colliderObject.AddComponent(); + colliderGroups[mmdRigidBody.CollisionGroup].Add(sphereCollider); + sphereCollider.radius = mmdRigidBody.Dimemsions.x; + break; + } + + if (bone.GetComponent() != null) { continue; } + Rigidbody rigidbody = bone.AddComponent(); + 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(); + if (jointToRigidbody == null) { continue; } + Rigidbody jointFromRigidbody = jointFromObj.GetComponent(); + if (jointFromRigidbody == null) + { + //この場合jointFromObjは基本的に体の一部などの始点 + jointFromRigidbody = jointFromObj.AddComponent(); + jointFromRigidbody.isKinematic = true; + } + //すでに向こう側から接続していたら接続しない + HingeJoint[] counterJoint = jointToObj.GetComponents(); + if (counterJoint.Any(x => x != null && jointFromRigidbody != null && x.connectedBody == jointFromRigidbody)) { continue; } + //残念ながら情報を落とす + HingeJoint joint = jointFromObj.AddComponent(); + 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 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 vertexMorphs = new List(); + 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; + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MMDModel.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MMDModel.cs.meta new file mode 100644 index 0000000..02a009f --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MMDModel.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3d691346906868a42b19a716a0ca2ee3 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MMDUnityConfig.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MMDUnityConfig.cs new file mode 100644 index 0000000..264f69f --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MMDUnityConfig.cs @@ -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); + } + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MMDUnityConfig.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MMDUnityConfig.cs.meta new file mode 100644 index 0000000..c2b5236 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MMDUnityConfig.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 43735cc6fa2ef754296beb18361c4b93 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MaterialLoader.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MaterialLoader.cs new file mode 100644 index 0000000..ec8058e --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MaterialLoader.cs @@ -0,0 +1,171 @@ +// ------------------------------------------------------------------------------ +// +// 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. +// +// ------------------------------------------------------------------------------ + +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; + } + } + +} + diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MaterialLoader.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MaterialLoader.cs.meta new file mode 100644 index 0000000..941eaa1 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MaterialLoader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c96bc2c33987dc744a12399c9e4af3ce +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MaterialMorphRemover.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MaterialMorphRemover.cs new file mode 100644 index 0000000..37d387f --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MaterialMorphRemover.cs @@ -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"); + } + } + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MaterialMorphRemover.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MaterialMorphRemover.cs.meta new file mode 100644 index 0000000..0483073 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/MaterialMorphRemover.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1a4d8655d04c12a45be046f9d8cd31de +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ModelPart.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ModelPart.cs new file mode 100644 index 0000000..7918296 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ModelPart.cs @@ -0,0 +1,43 @@ +// ------------------------------------------------------------------------------ +// +// 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. +// +// ------------------------------------------------------------------------------ + +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;} + } +} + diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ModelPart.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ModelPart.cs.meta new file mode 100644 index 0000000..fa6828a --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/ModelPart.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 29488fac476a8cf44ae86fb0c0ccb5e9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/PMXModelLoader.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/PMXModelLoader.cs new file mode 100644 index 0000000..a6c85da --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/PMXModelLoader.cs @@ -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 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(); + 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(); + #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 LoadPMXModel(string path, RuntimeAnimatorController runtimeAnimatorController, bool autoShowModel = true) + { + return await LoadPMXModel(path, runtimeAnimatorController, null, autoShowModel); + } + + public async static Task LoadPMXModel(string path, RuntimeAnimatorController runtimeAnimatorController) + { + return await LoadPMXModel(path, runtimeAnimatorController, null); + } + + public async static Task LoadPMXModel(string path, bool autoShowModel = true) + { + return await LoadPMXModel(path, null, null, autoShowModel); + } +} diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/PMXModelLoader.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/PMXModelLoader.cs.meta new file mode 100644 index 0000000..bedd83f --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/PMXModelLoader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 39b14547e60be694ea7d26990aa49e91 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/TextureLoader.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/TextureLoader.cs new file mode 100644 index 0000000..cc0fb5f --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/TextureLoader.cs @@ -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 SysToonNames = new HashSet(); + + private readonly Dictionary _textureMap = new Dictionary(); + + 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; + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/TextureLoader.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/TextureLoader.cs.meta new file mode 100644 index 0000000..375d610 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/TextureLoader.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1f3af3954c1f52a4f9be720b11a77a5c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/TextureScale.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/TextureScale.cs new file mode 100644 index 0000000..2034448 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/TextureScale.cs @@ -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); + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/TextureScale.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/TextureScale.cs.meta new file mode 100644 index 0000000..d0f71c5 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/TextureScale.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c343dd8f2f3826b46aae4a5a03d11559 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/Utils.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/Utils.cs new file mode 100644 index 0000000..4164c5d --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Unity3D/Utils.cs @@ -0,0 +1,107 @@ +// ------------------------------------------------------------------------------ +// +// 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. +// +// ------------------------------------------------------------------------------ + +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 ArrayToList(T[] src, int srcIndex, int length) { + var ret = new List (length); + var endPos = srcIndex + length; + for (var i=srcIndex; i + { + private int _count; + + private readonly Queue _queue = new Queue(); + + private readonly int _maxSize; + + public BlockingQueue(int maxSize = int.MaxValue) + { + _maxSize = maxSize; + } + + public int MaxSize + { + get { return _maxSize; } + } + + public int Count + { + get + { + lock (_queue) + { + return _count; + } + } + } + + public T DequeueNonBlocking() + { + lock (_queue) + { + if (_count <= 0) + { + return default(T); + } + + _count--; + + var ret = _queue.Dequeue(); + Monitor.PulseAll(_queue); + return ret; + } + } + + public T Dequeue() + { + lock (_queue) + { + // If we have items remaining in the queue, skip over this. + while (_count <= 0) + { + Monitor.Wait(_queue); + } + + _count--; + + var ret = _queue.Dequeue(); + Monitor.PulseAll(_queue); + return ret; + } + } + + public int Enqueue(T data) + { + if (data == null) + { + throw new ArgumentNullException("data is null"); + } + + lock (_queue) + { + while (_count >= _maxSize) + { + Monitor.Wait(_queue); + } + + _queue.Enqueue(data); + + _count++; + + Monitor.PulseAll(_queue); + return _count; + } + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/BlockingQueue.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/BlockingQueue.cs.meta new file mode 100644 index 0000000..3fedb84 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/BlockingQueue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ee362629fc8ffc94b9188285001e0ce2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/LogUtil.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/LogUtil.cs new file mode 100644 index 0000000..8e6a6bd --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/LogUtil.cs @@ -0,0 +1,27 @@ +using System; + +namespace LibMMD.Util +{ + public static class LogUtil + { + public static void Debug(string format, params object[] args) + { + + } + + public static void Info(string format, params object[] args) + { + + } + + public static void Warn(string format, params object[] args) + { + + } + + public static void Error(string format, params object[] args) + { + + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/LogUtil.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/LogUtil.cs.meta new file mode 100644 index 0000000..03d666b --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/LogUtil.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: babd7022c37a7544989f502bd0f3e8d7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MMDReaderUtil.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MMDReaderUtil.cs new file mode 100644 index 0000000..a2ed172 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MMDReaderUtil.cs @@ -0,0 +1,125 @@ +using System; +using System.IO; +using System.Text; +using LibMMD.Reader; +using UnityEngine; + +namespace LibMMD.Util +{ + public static class MMDReaderUtil + { + const float WorldSizeAmplifier = 0.08f; + + public static string ReadStringFixedLength(BinaryReader reader, int length, Encoding encoding) + { + if (length < 0) + { + throw new MMDFileParseException("pmx string length is negative"); + } + if (length == 0) + { + return ""; + } + var bytes = reader.ReadBytes(length); + var str = encoding.GetString(bytes); + var end = str.IndexOf("\0", StringComparison.Ordinal); + if (end >= 0) + { + str = str.Substring(0, end); + } + return str; + } + + public static string ReadSizedString(BinaryReader reader, Encoding encoding) + { + var length = reader.ReadInt32(); + return ReadStringFixedLength(reader, length, encoding); + } + + public static Vector4 ReadVector4(BinaryReader reader) + { + var ret = new Vector4(); + ret[0] = MathUtil.NanToZero(reader.ReadSingle()); + ret[1] = MathUtil.NanToZero(reader.ReadSingle()); + ret[2] = MathUtil.NanToZero(reader.ReadSingle()); + ret[3] = MathUtil.NanToZero(reader.ReadSingle()); + return ret; + } + + public static Quaternion ReadQuaternion(BinaryReader reader) + { + var ret = new Quaternion(); + ret.x = -MathUtil.NanToZero(reader.ReadSingle()); + ret.y = MathUtil.NanToZero(reader.ReadSingle()); + ret.z = -MathUtil.NanToZero(reader.ReadSingle()); + ret.w = MathUtil.NanToZero(reader.ReadSingle()); + return ret; + } + + public static Vector3 ReadVector3(BinaryReader reader) + { + return ReadAmpVector3(reader, WorldSizeAmplifier); + } + + public static Vector3 ReadAmpVector3(BinaryReader reader, float amp) + { + var ret = new Vector3(); + ret[0] = -MathUtil.NanToZero(reader.ReadSingle()) * amp; + ret[1] = MathUtil.NanToZero(reader.ReadSingle()) * amp; + ret[2] = -MathUtil.NanToZero(reader.ReadSingle()) * amp; + return ret; + } + + public static Vector3 ReadRawCoordinateVector3(BinaryReader reader) + { + var ret = new Vector3(); + ret[0] = MathUtil.NanToZero(reader.ReadSingle()) * WorldSizeAmplifier; + ret[1] = MathUtil.NanToZero(reader.ReadSingle()) * WorldSizeAmplifier; + ret[2] = MathUtil.NanToZero(reader.ReadSingle()) * WorldSizeAmplifier; + return ret; + } + + + public static Vector2 ReadVector2(BinaryReader reader) + { + var ret = new Vector2(); + ret[0] = MathUtil.NanToZero(reader.ReadSingle()); + ret[1] = MathUtil.NanToZero(reader.ReadSingle()); + return ret; + } + + public static int ReadIndex(BinaryReader reader, int size) + { + switch (size) + { + case 1: + return reader.ReadSByte(); + case 2: + return reader.ReadUInt16(); + case 4: + return reader.ReadInt32(); + default: + throw new MMDFileParseException("invalid index size: " + size); + } + } + + public static Color ReadColor(BinaryReader reader, bool readA) + { + var ret = new Color + { + r = reader.ReadSingle(), + g = reader.ReadSingle(), + b = reader.ReadSingle(), + a = readA ? reader.ReadSingle() : 1.0f + }; + return ret; + } + + public static bool Eof(BinaryReader binaryReader) + { + var bs = binaryReader.BaseStream; + return (bs.Position == bs.Length); + } + + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MMDReaderUtil.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MMDReaderUtil.cs.meta new file mode 100644 index 0000000..bc3cc13 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MMDReaderUtil.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 09e79f8045c6b81438f0b24590059aea +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MMDTextureUtil.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MMDTextureUtil.cs new file mode 100644 index 0000000..a6da4b0 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MMDTextureUtil.cs @@ -0,0 +1,31 @@ +using LibMMD.Material; + +namespace LibMMD.Util +{ + public static class MMDTextureUtil + { + private static readonly string[] GlobalToonNames = + { + "toon0.bmp", + "toon01.bmp", + "toon02.bmp", + "toon03.bmp", + "toon04.bmp", + "toon05.bmp", + "toon06.bmp", + "toon07.bmp", + "toon08.bmp", + "toon09.bmp", + "toon10.bmp" + }; + + public static MMDTexture GetGlobalToon(int index, string rootPath) + { + if (index >= 0 && index < GlobalToonNames.Length - 1) + { + return new MMDTexture(GlobalToonNames[index + 1]); + } + return null; + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MMDTextureUtil.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MMDTextureUtil.cs.meta new file mode 100644 index 0000000..905e4b1 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MMDTextureUtil.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 62a8a9476e1c6cb4591487bbb1cbcb7c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MathUtil.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MathUtil.cs new file mode 100644 index 0000000..fe48443 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MathUtil.cs @@ -0,0 +1,277 @@ +using System; +using UnityEngine; +using Quaternion = UnityEngine.Quaternion; +using Vector3 = UnityEngine.Vector3; + +namespace LibMMD.Util +{ + public static class MathUtil + { + public static Matrix4x4 Matrix4X4MuliplyFloat(Matrix4x4 mat, float val) + { + return new Matrix4x4 + { + m00 = mat.m00 * val, + m01 = mat.m01 * val, + m02 = mat.m02 * val, + m03 = mat.m03 * val, + m10 = mat.m10 * val, + m11 = mat.m11 * val, + m12 = mat.m12 * val, + m13 = mat.m13 * val, + m20 = mat.m20 * val, + m21 = mat.m21 * val, + m22 = mat.m22 * val, + m23 = mat.m23 * val, + m30 = mat.m30 * val, + m31 = mat.m31 * val, + m32 = mat.m32 * val, + m33 = mat.m33 * val + }; + } + + public static Matrix4x4 Matrix4X4Add(Matrix4x4 mat1, Matrix4x4 mat2) + { + return new Matrix4x4 + { + m00 = mat1.m00 + mat2.m00, + m01 = mat1.m01 + mat2.m01, + m02 = mat1.m02 + mat2.m02, + m03 = mat1.m03 + mat2.m03, + m10 = mat1.m10 + mat2.m10, + m11 = mat1.m11 + mat2.m11, + m12 = mat1.m12 + mat2.m12, + m13 = mat1.m13 + mat2.m13, + m20 = mat1.m20 + mat2.m20, + m21 = mat1.m21 + mat2.m21, + m22 = mat1.m22 + mat2.m22, + m23 = mat1.m23 + mat2.m23, + m30 = mat1.m30 + mat2.m30, + m31 = mat1.m31 + mat2.m31, + m32 = mat1.m32 + mat2.m32, + m33 = mat1.m33 + mat2.m33 + }; + } + + public static Matrix4x4 QuaternionToMatrix4X4(Quaternion quaternion) + { + return Matrix4x4.TRS(Vector3.zero, quaternion, Vector3.one); + } + + public static Vector3 GetTransFromMatrix4X4(Matrix4x4 mat) + { + return new Vector3(mat.m03, mat.m13, mat.m23); + } + + public static void SetTransToMatrix4X4(Vector3 trans, ref Matrix4x4 mat) + { + mat.m03 = trans[0]; + mat.m13 = trans[1]; + mat.m23 = trans[2]; + } + + public static Vector3 Matrix4x4ColDowngrade(Matrix4x4 mat, int col) + { + return new Vector3(mat[0, col], mat[1, col], mat[2, col]); + } + + public static Vector3 QuaternionToXyz(Quaternion quaternion) + { + var ii = quaternion.x * quaternion.x; + var jj = quaternion.y * quaternion.y; + var kk = quaternion.z * quaternion.z; + var ei = quaternion.w * quaternion.x; + var ej = quaternion.w * quaternion.y; + var ek = quaternion.w * quaternion.z; + var ij = quaternion.x * quaternion.y; + var ik = quaternion.x * quaternion.z; + var jk = quaternion.y * quaternion.z; + Vector3 result; + result.x = (float) Math.Atan2(2.0f * (ei - jk), 1 - 2.0f * (ii + jj)); + result.y = (float) Math.Asin(2.0f * (ej + ik)); + result.z = (float) Math.Atan2(2.0f * (ek - ij), 1 - 2.0f * (jj + kk)); + return result; + } + + public static Vector3 QuaternionToXzy(Quaternion quaternion) + { + var ii = quaternion.x * quaternion.x; + var jj = quaternion.y * quaternion.y; + var kk = quaternion.z * quaternion.z; + var ei = quaternion.w * quaternion.x; + var ej = quaternion.w * quaternion.y; + var ek = quaternion.w * quaternion.z; + var ij = quaternion.x * quaternion.y; + var ik = quaternion.x * quaternion.z; + var jk = quaternion.y * quaternion.z; + Vector3 result; + result.x = (float) Math.Atan2(2.0f * (ei + jk), 1 - 2.0f * (ii + kk)); + result.y = (float) Math.Atan2(2.0f * (ej + ik), 1 - 2.0f * (jj + kk)); + result.z = (float) Math.Asin(2.0f * (ek - ij)); + return result; + } + + public static Vector3 QuaternionToYxz(Quaternion quaternion) + { + var ii = quaternion.x * quaternion.x; + var jj = quaternion.y * quaternion.y; + var kk = quaternion.z * quaternion.z; + var ei = quaternion.w * quaternion.x; + var ej = quaternion.w * quaternion.y; + var ek = quaternion.w * quaternion.z; + var ij = quaternion.x * quaternion.y; + var ik = quaternion.x * quaternion.z; + var jk = quaternion.y * quaternion.z; + Vector3 result; + result.x = (float) Math.Asin(2.0f * (ei - jk)); + result.y = (float) Math.Atan2(2.0f * (ej + ik), 1 - 2.0f * (ii + jj)); + result.z = (float) Math.Atan2(2.0f * (ek + ij), 1 - 2.0f * (ii + kk)); + return result; + } + + public static Vector3 QuaternionToYzx(Quaternion quaternion) + { + var ii = quaternion.x * quaternion.x; + var jj = quaternion.y * quaternion.y; + var kk = quaternion.z * quaternion.z; + var ei = quaternion.w * quaternion.x; + var ej = quaternion.w * quaternion.y; + var ek = quaternion.w * quaternion.z; + var ij = quaternion.x * quaternion.y; + var ik = quaternion.x * quaternion.z; + var jk = quaternion.y * quaternion.z; + Vector3 result; + result.x = (float) Math.Atan2(2.0f * (ei - jk), 1 - 2.0f * (ii + kk)); + result.y = (float) Math.Atan2(2.0f * (ej - ik), 1 - 2.0f * (jj + kk)); + result.z = (float) Math.Asin(2.0f * (ek + ij)); + return result; + } + + public static Vector3 QuaternionToZxy(Quaternion quaternion) + { + var ii = quaternion.x * quaternion.x; + var jj = quaternion.y * quaternion.y; + var kk = quaternion.z * quaternion.z; + var ei = quaternion.w * quaternion.x; + var ej = quaternion.w * quaternion.y; + var ek = quaternion.w * quaternion.z; + var ij = quaternion.x * quaternion.y; + var ik = quaternion.x * quaternion.z; + var jk = quaternion.y * quaternion.z; + Vector3 result; + result.x = (float) Math.Asin(2.0f * (ei + jk)); + result.y = (float) Math.Atan2(2.0f * (ej - ik), 1 - 2.0f * (ii + jj)); + result.z = (float) Math.Atan2(2.0f * (ek - ij), 1 - 2.0f * (ii + kk)); + return result; + } + + public static Vector3 QuaternionToZyx(Quaternion quaternion) + { + var ii = quaternion.x * quaternion.x; + var jj = quaternion.y * quaternion.y; + var kk = quaternion.z * quaternion.z; + var ei = quaternion.w * quaternion.x; + var ej = quaternion.w * quaternion.y; + var ek = quaternion.w * quaternion.z; + var ij = quaternion.x * quaternion.y; + var ik = quaternion.x * quaternion.z; + var jk = quaternion.y * quaternion.z; + Vector3 result; + result.x = (float) Math.Atan2(2.0f * (ei + jk), 1 - 2.0f * (ii + jj)); + result.y = (float) Math.Asin(2.0f * (ej - ik)); + result.z = (float) Math.Atan2(2.0f * (ek + ij), 1 - 2.0f * (jj + kk)); + return result; + } + + public static Quaternion XyzToQuaternion(Vector3 euler) { + var cx = Math.Cos(euler.x*0.5f); + var sx = Math.Sin(euler.x*0.5f); + var cy = Math.Cos(euler.y*0.5f); + var sy = Math.Sin(euler.y*0.5f); + var cz = Math.Cos(euler.z*0.5f); + var sz = Math.Sin(euler.z*0.5f); + Quaternion result; + result.w = (float) (cx*cy*cz-sx*sy*sz); + result.x = (float) (sx*cy*cz+cx*sy*sz); + result.y = (float) (cx*sy*cz-sx*cy*sz); + result.z = (float) (sx*sy*cz+cx*cy*sz); + return result; + } + public static Quaternion XzyToQuaternion(Vector3 euler) { + var cx = Math.Cos(euler.x*0.5f); + var sx = Math.Sin(euler.x*0.5f); + var cy = Math.Cos(euler.y*0.5f); + var sy = Math.Sin(euler.y*0.5f); + var cz = Math.Cos(euler.z*0.5f); + var sz = Math.Sin(euler.z*0.5f); + Quaternion result; + result.w = (float) (cx*cy*cz+sx*sy*sz); + result.x = (float) (sx*cy*cz-cx*sy*sz); + result.y = (float) (cx*sy*cz-sx*cy*sz); + result.z = (float) (cx*cy*sz+sx*sy*cz); + return result; + } + public static Quaternion YxzToQuaternion(Vector3 euler) { + var cx = Math.Cos(euler.x*0.5f); + var sx = Math.Sin(euler.x*0.5f); + var cy = Math.Cos(euler.y*0.5f); + var sy = Math.Sin(euler.y*0.5f); + var cz = Math.Cos(euler.z*0.5f); + var sz = Math.Sin(euler.z*0.5f); + Quaternion result; + result.w = (float) (cx*cy*cz+sx*sy*sz); + result.x = (float) (sx*cy*cz+cx*sy*sz); + result.y = (float) (cx*sy*cz-sx*cy*sz); + result.z = (float) (cx*cy*sz-sx*sy*cz); + return result; + } + public static Quaternion YzxToQuaternion(Vector3 euler) { + var cx = Math.Cos(euler.x*0.5f); + var sx = Math.Sin(euler.x*0.5f); + var cy = Math.Cos(euler.y*0.5f); + var sy = Math.Sin(euler.y*0.5f); + var cz = Math.Cos(euler.z*0.5f); + var sz = Math.Sin(euler.z*0.5f); + Quaternion result; + result.w = (float) (cx*cy*cz-sx*sy*sz); + result.x = (float) (sx*cy*cz+cx*sy*sz); + result.y = (float) (cx*sy*cz+sx*cy*sz); + result.z = (float) (cx*cy*sz-sx*sy*cz); + return result; + } + public static Quaternion ZxyToQuaternion(Vector3 euler) { + var cx = Math.Cos(euler.x*0.5f); + var sx = Math.Sin(euler.x*0.5f); + var cy = Math.Cos(euler.y*0.5f); + var sy = Math.Sin(euler.y*0.5f); + var cz = Math.Cos(euler.z*0.5f); + var sz = Math.Sin(euler.z*0.5f); + Quaternion result; + result.w = (float) (cx*cy*cz-sx*sy*sz); + result.x = (float) (sx*cy*cz-cx*sy*sz); + result.y = (float) (cx*sy*cz+sx*cy*sz); + result.z = (float) (cx*cy*sz+sx*sy*cz); + return result; + } + public static Quaternion ZYXToQuaternion(Vector3 euler) { + var cx = Math.Cos(euler.x*0.5f); + var sx = Math.Sin(euler.x*0.5f); + var cy = Math.Cos(euler.y*0.5f); + var sy = Math.Sin(euler.y*0.5f); + var cz = Math.Cos(euler.z*0.5f); + var sz = Math.Sin(euler.z*0.5f); + Quaternion result; + result.w = (float) (cx*cy*cz+sx*sy*sz); + result.x = (float) (sx*cy*cz-cx*sy*sz); + result.y = (float) (cx*sy*cz+sx*cy*sz); + result.z = (float) (cx*cy*sz-sx*sy*cz); + return result; + } + + public static float NanToZero(float f) + { + return float.IsNaN(f) ? 0.0f : f; + } + + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MathUtil.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MathUtil.cs.meta new file mode 100644 index 0000000..5606c3e --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MathUtil.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6530efcfb90ab7a4a979a57a9b4bfe7e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MatrixExtensions.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MatrixExtensions.cs new file mode 100644 index 0000000..88b2af3 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MatrixExtensions.cs @@ -0,0 +1,40 @@ +namespace LibMMD.Util +{ + using UnityEngine; + + public static class MatrixExtensions + { + public static Quaternion ExtractRotation(this Matrix4x4 matrix) + { + Vector3 forward; + forward.x = matrix.m02; + forward.y = matrix.m12; + forward.z = matrix.m22; + + Vector3 upwards; + upwards.x = matrix.m01; + upwards.y = matrix.m11; + upwards.z = matrix.m21; + + return Quaternion.LookRotation(forward, upwards); + } + + public static Vector3 ExtractPosition(this Matrix4x4 matrix) + { + Vector3 position; + position.x = matrix.m03; + position.y = matrix.m13; + position.z = matrix.m23; + return position; + } + + public static Vector3 ExtractScale(this Matrix4x4 matrix) + { + Vector3 scale; + scale.x = new Vector4(matrix.m00, matrix.m10, matrix.m20, matrix.m30).magnitude; + scale.y = new Vector4(matrix.m01, matrix.m11, matrix.m21, matrix.m31).magnitude; + scale.z = new Vector4(matrix.m02, matrix.m12, matrix.m22, matrix.m32).magnitude; + return scale; + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MatrixExtensions.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MatrixExtensions.cs.meta new file mode 100644 index 0000000..3aff5e7 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/MatrixExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d6aa1afffc18d7442a0868b263a9649c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/SynchronizedQueue.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/SynchronizedQueue.cs new file mode 100644 index 0000000..f6124ee --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/SynchronizedQueue.cs @@ -0,0 +1,33 @@ +using System.Collections.Generic; + +namespace LibMMD.Util +{ + public class SynchronizedQueue + { + private readonly Queue _queue = new Queue(); + + public void Enqueue(T val) + { + lock (_queue) + { + _queue.Enqueue(val); + } + } + + public T Take() + { + lock (_queue) + { + return _queue.Count <= 0 ? default(T) : _queue.Dequeue(); + } + } + + public int Count() + { + lock (_queue) + { + return _queue.Count; + } + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/SynchronizedQueue.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/SynchronizedQueue.cs.meta new file mode 100644 index 0000000..4c30271 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/SynchronizedQueue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 173dfc038c2acc847922d19569b1fc38 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/Tools.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/Tools.cs new file mode 100644 index 0000000..2bfd153 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/Tools.cs @@ -0,0 +1,10 @@ +using System.Text; + +namespace LibMMD.Util +{ + public static class Tools + { + public static readonly Encoding JapaneseEncoding = Encoding.GetEncoding(932); + public const float MmdMathConstEps = (float) 1.0e-7; + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/Tools.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/Tools.cs.meta new file mode 100644 index 0000000..1a094e5 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/Tools.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c38c1832b9c7a004f8cc6624b772ee32 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/TransformExtensions.cs b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/TransformExtensions.cs new file mode 100644 index 0000000..34f3bf4 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/TransformExtensions.cs @@ -0,0 +1,14 @@ +using UnityEngine; + +namespace LibMMD.Util +{ + public static class TransformExtensions + { + public static void FromMatrix(this Transform transform, Matrix4x4 matrix) + { + transform.localScale = matrix.ExtractScale(); + transform.rotation = matrix.ExtractRotation(); + transform.position = matrix.ExtractPosition(); + } + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/TransformExtensions.cs.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/TransformExtensions.cs.meta new file mode 100644 index 0000000..6f44e30 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/Util/TransformExtensions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8f9aee4e9b09a134c8bc6e55f76f6df1 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/libmmd-for-unity LICENSE.txt b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/libmmd-for-unity LICENSE.txt new file mode 100644 index 0000000..89b1933 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/libmmd-for-unity LICENSE.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2017, x3bits (x3bits@sina.com) +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/libmmd-for-unity LICENSE.txt.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/libmmd-for-unity LICENSE.txt.meta new file mode 100644 index 0000000..e677bec --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/LibMMD/libmmd-for-unity LICENSE.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 008cecd1ac3cfb54693659eed2a5d9cc +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/README.md b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/README.md new file mode 100644 index 0000000..43a3827 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/README.md @@ -0,0 +1,12 @@ +# UnityPMXImporter + + pmxファイル(mmdのモデルファイル)をUnityに直接(変換なしに、動的に、スクリプトから)読み込むためのコード + + +使用に特に制限は設けませんが、公序良俗の範囲でお願いします。 +また、このコードを使用して生じた問題について制作者は責任を負いません。 +答えられるかはわかりませんが、不具合や要望があれば軽々しくご連絡ください。 + + +Hobosore@hobosore +hobosore@gmail.com diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/README.md.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/README.md.meta new file mode 100644 index 0000000..efe4167 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 3eaf017b535b8d240a646990b613a01b +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM.meta new file mode 100644 index 0000000..657dfb1 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b66aa35b290568844987f3015a66339c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM LICENSE.txt b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM LICENSE.txt new file mode 100644 index 0000000..f10cd28 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM LICENSE.txt @@ -0,0 +1,23 @@ +MIT License + +Copyright (c) 2018 DWANGO Co., Ltd. for UniVRM +Copyright (c) 2018 ousttrue for UniGLTF, UniHumanoid +Copyright (c) 2018 Masataka SUMI for MToon + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM LICENSE.txt.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM LICENSE.txt.meta new file mode 100644 index 0000000..a05fb0a --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM LICENSE.txt.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 782e3aab60332484d9f499182cc213c8 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM.meta new file mode 100644 index 0000000..8b6f129 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b41579dc46366974386ef7e1172b3b6c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources.meta new file mode 100644 index 0000000..2857110 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: bd4a0ab53875864449abe274b3171acb +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders.meta new file mode 100644 index 0000000..040d158 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 43c3eeb93005cb3438391ddcdf5e651c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMShaders.shadervariants b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMShaders.shadervariants new file mode 100644 index 0000000..dc5583c --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMShaders.shadervariants @@ -0,0 +1,33 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!200 &20000000 +ShaderVariantCollection: + m_ObjectHideFlags: 0 + m_PrefabParentObject: {fileID: 0} + m_PrefabInternal: {fileID: 0} + m_Name: VRMShaders + m_Shaders: + data: + first: {fileID: 4800000, guid: 1a70c9898704e1a4691843883f5101af, type: 3} + second: + variants: [] + data: + first: {fileID: 4800000, guid: 429a3203ab2959741aab76fa2856b450, type: 3} + second: + variants: [] + data: + first: {fileID: 4800000, guid: 4c9ce97af40038f45811fc4b0975a483, type: 3} + second: + variants: [] + data: + first: {fileID: 4800000, guid: 8c17b56f4bf084c47872edcb95237e4a, type: 3} + second: + variants: [] + data: + first: {fileID: 4800000, guid: df359ad0838642d4fa0339514fcbbb2d, type: 3} + second: + variants: [] + data: + first: {fileID: 4800000, guid: 1a97144e4ad27a04aafd70f7b915cedb, type: 3} + second: + variants: [] diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMShaders.shadervariants.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMShaders.shadervariants.meta new file mode 100644 index 0000000..6cccfe0 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMShaders.shadervariants.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 486ebb794ada0de41be4f35c56876f82 +timeCreated: 1520840003 +licenseType: Free +NativeFormatImporter: + mainObjectFileID: 20000000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitCutout.shader b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitCutout.shader new file mode 100644 index 0000000..33052c9 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitCutout.shader @@ -0,0 +1,61 @@ +Shader "VRM/UnlitCutout" +{ +Properties { + _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {} + _Cutoff ("Alpha cutoff", Range(0,1)) = 0.5 +} +SubShader { + Tags {"Queue"="AlphaTest" "IgnoreProjector"="True" "RenderType"="TransparentCutout"} + LOD 100 + + Lighting Off + + Pass { + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #pragma target 2.0 + #pragma multi_compile_fog + + #include "UnityCG.cginc" + + struct appdata_t { + float4 vertex : POSITION; + float2 texcoord : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID + }; + + struct v2f { + float4 vertex : SV_POSITION; + float2 texcoord : TEXCOORD0; + UNITY_FOG_COORDS(1) + UNITY_VERTEX_OUTPUT_STEREO + }; + + sampler2D _MainTex; + float4 _MainTex_ST; + fixed _Cutoff; + + v2f vert (appdata_t v) + { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.vertex = UnityObjectToClipPos(v.vertex); + o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex); + UNITY_TRANSFER_FOG(o,o.vertex); + return o; + } + + fixed4 frag (v2f i) : SV_Target + { + fixed4 col = tex2D(_MainTex, i.texcoord); + clip(col.a - _Cutoff); + UNITY_APPLY_FOG(i.fogCoord, col); + return col; + } + ENDCG + } +} + +} diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitCutout.shader.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitCutout.shader.meta new file mode 100644 index 0000000..aefa975 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitCutout.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 4c9ce97af40038f45811fc4b0975a483 +timeCreated: 1522661614 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTexture.shader b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTexture.shader new file mode 100644 index 0000000..edb666f --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTexture.shader @@ -0,0 +1,58 @@ +Shader "VRM/UnlitTexture" +{ + Properties + { + _MainTex ("Texture", 2D) = "white" {} + } + SubShader + { + Tags { "RenderType"="Opaque" } + LOD 100 + + Pass + { + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + // make fog work + #pragma multi_compile_fog + + #include "UnityCG.cginc" + + struct appdata + { + float4 vertex : POSITION; + float2 uv : TEXCOORD0; + }; + + struct v2f + { + float2 uv : TEXCOORD0; + UNITY_FOG_COORDS(1) + float4 vertex : SV_POSITION; + }; + + sampler2D _MainTex; + float4 _MainTex_ST; + + v2f vert (appdata v) + { + v2f o; + o.vertex = UnityObjectToClipPos(v.vertex); + o.uv = TRANSFORM_TEX(v.uv, _MainTex); + UNITY_TRANSFER_FOG(o,o.vertex); + return o; + } + + fixed4 frag (v2f i) : SV_Target + { + // sample the texture + fixed4 col = tex2D(_MainTex, i.uv); + // apply fog + UNITY_APPLY_FOG(i.fogCoord, col); + return col; + } + ENDCG + } + } +} diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTexture.shader.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTexture.shader.meta new file mode 100644 index 0000000..b536792 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTexture.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 1a70c9898704e1a4691843883f5101af +timeCreated: 1522661614 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTransparent.shader b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTransparent.shader new file mode 100644 index 0000000..4cf8e9e --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTransparent.shader @@ -0,0 +1,61 @@ +Shader "VRM/UnlitTransparent" +{ +Properties { + _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {} +} + +SubShader { + Tags {"Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent"} + LOD 100 + + ZWrite Off + Blend SrcAlpha OneMinusSrcAlpha + BlendOp Add, Max + + Pass { + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #pragma target 2.0 + #pragma multi_compile_fog + + #include "UnityCG.cginc" + + struct appdata_t { + float4 vertex : POSITION; + float2 texcoord : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID + }; + + struct v2f { + float4 vertex : SV_POSITION; + float2 texcoord : TEXCOORD0; + UNITY_FOG_COORDS(1) + UNITY_VERTEX_OUTPUT_STEREO + }; + + sampler2D _MainTex; + float4 _MainTex_ST; + + v2f vert (appdata_t v) + { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.vertex = UnityObjectToClipPos(v.vertex); + o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex); + UNITY_TRANSFER_FOG(o,o.vertex); + return o; + } + + fixed4 frag (v2f i) : SV_Target + { + fixed4 col = tex2D(_MainTex, i.texcoord); + UNITY_APPLY_FOG(i.fogCoord, col); + return col; + } + ENDCG + } +} + +} diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTransparent.shader.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTransparent.shader.meta new file mode 100644 index 0000000..a2e35ec --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTransparent.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: df359ad0838642d4fa0339514fcbbb2d +timeCreated: 1522661614 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTransparentZWrite.shader b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTransparentZWrite.shader new file mode 100644 index 0000000..70d5ea9 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTransparentZWrite.shader @@ -0,0 +1,61 @@ +Shader "VRM/UnlitTransparentZWrite" +{ +Properties { + _MainTex ("Base (RGB) Trans (A)", 2D) = "white" {} +} + +SubShader { + Tags {"Queue"="AlphaTest+150" "IgnoreProjector"="True" "RenderType"="Transparent"} + LOD 100 + + ZWrite On + Blend SrcAlpha OneMinusSrcAlpha + BlendOp Add, Max + + Pass { + CGPROGRAM + #pragma vertex vert + #pragma fragment frag + #pragma target 2.0 + #pragma multi_compile_fog + + #include "UnityCG.cginc" + + struct appdata_t { + float4 vertex : POSITION; + float2 texcoord : TEXCOORD0; + UNITY_VERTEX_INPUT_INSTANCE_ID + }; + + struct v2f { + float4 vertex : SV_POSITION; + float2 texcoord : TEXCOORD0; + UNITY_FOG_COORDS(1) + UNITY_VERTEX_OUTPUT_STEREO + }; + + sampler2D _MainTex; + float4 _MainTex_ST; + + v2f vert (appdata_t v) + { + v2f o; + UNITY_SETUP_INSTANCE_ID(v); + UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o); + o.vertex = UnityObjectToClipPos(v.vertex); + o.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex); + UNITY_TRANSFER_FOG(o,o.vertex); + return o; + } + + fixed4 frag (v2f i) : SV_Target + { + fixed4 col = tex2D(_MainTex, i.texcoord); + UNITY_APPLY_FOG(i.fogCoord, col); + return col; + } + ENDCG + } +} + +} diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTransparentZWrite.shader.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTransparentZWrite.shader.meta new file mode 100644 index 0000000..b7cb6fe --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VRM/UniVRM/Resources/Shaders/VRMUnlitTransparentZWrite.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 429a3203ab2959741aab76fa2856b450 +timeCreated: 1522661614 +licenseType: Free +ShaderImporter: + defaultTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VoidShader.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VoidShader.meta new file mode 100644 index 0000000..faf9e82 --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VoidShader.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a98762fc92e6e2343be7299617b72380 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VoidShader/CustomVoidShader.shader b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VoidShader/CustomVoidShader.shader new file mode 100644 index 0000000..84cf52e --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VoidShader/CustomVoidShader.shader @@ -0,0 +1,8 @@ +Shader "Custom/VoidShader" +{ + SubShader + { + Colormask 0 Zwrite Off + Pass{} + } +} \ No newline at end of file diff --git a/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VoidShader/CustomVoidShader.shader.meta b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VoidShader/CustomVoidShader.shader.meta new file mode 100644 index 0000000..0052fbc --- /dev/null +++ b/Assets/Scripts/Exporters/UnityPMXRuntimeLoader/VoidShader/CustomVoidShader.shader.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: b863df65a439dcb44a22a21360e2053f +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/VMDRecorder.meta b/Assets/Scripts/Exporters/VMDRecorder.meta similarity index 100% rename from Assets/Scripts/VMDRecorder.meta rename to Assets/Scripts/Exporters/VMDRecorder.meta diff --git a/Assets/Scripts/Exporters/VMDRecorder/LICENSE b/Assets/Scripts/Exporters/VMDRecorder/LICENSE new file mode 100644 index 0000000..1ec518e --- /dev/null +++ b/Assets/Scripts/Exporters/VMDRecorder/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 hobosore + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Assets/Scripts/VMDRecorder/LICENSE.meta b/Assets/Scripts/Exporters/VMDRecorder/LICENSE.meta similarity index 100% rename from Assets/Scripts/VMDRecorder/LICENSE.meta rename to Assets/Scripts/Exporters/VMDRecorder/LICENSE.meta diff --git a/Assets/Scripts/VMDRecorder/UnityCameraVMDRecorder.cs b/Assets/Scripts/Exporters/VMDRecorder/UnityCameraVMDRecorder.cs similarity index 100% rename from Assets/Scripts/VMDRecorder/UnityCameraVMDRecorder.cs rename to Assets/Scripts/Exporters/VMDRecorder/UnityCameraVMDRecorder.cs diff --git a/Assets/Scripts/VMDRecorder/UnityCameraVMDRecorder.cs.meta b/Assets/Scripts/Exporters/VMDRecorder/UnityCameraVMDRecorder.cs.meta similarity index 100% rename from Assets/Scripts/VMDRecorder/UnityCameraVMDRecorder.cs.meta rename to Assets/Scripts/Exporters/VMDRecorder/UnityCameraVMDRecorder.cs.meta diff --git a/Assets/Scripts/VMDRecorder/UnityHumanoidVMDRecorder.cs b/Assets/Scripts/Exporters/VMDRecorder/UnityHumanoidVMDRecorder.cs similarity index 100% rename from Assets/Scripts/VMDRecorder/UnityHumanoidVMDRecorder.cs rename to Assets/Scripts/Exporters/VMDRecorder/UnityHumanoidVMDRecorder.cs diff --git a/Assets/Scripts/VMDRecorder/UnityHumanoidVMDRecorder.cs.meta b/Assets/Scripts/Exporters/VMDRecorder/UnityHumanoidVMDRecorder.cs.meta similarity index 100% rename from Assets/Scripts/VMDRecorder/UnityHumanoidVMDRecorder.cs.meta rename to Assets/Scripts/Exporters/VMDRecorder/UnityHumanoidVMDRecorder.cs.meta diff --git a/Assets/Scripts/VMDRecorder/UnityVMDQuaternionExtentions.cs b/Assets/Scripts/Exporters/VMDRecorder/UnityVMDQuaternionExtentions.cs similarity index 100% rename from Assets/Scripts/VMDRecorder/UnityVMDQuaternionExtentions.cs rename to Assets/Scripts/Exporters/VMDRecorder/UnityVMDQuaternionExtentions.cs diff --git a/Assets/Scripts/VMDRecorder/UnityVMDQuaternionExtentions.cs.meta b/Assets/Scripts/Exporters/VMDRecorder/UnityVMDQuaternionExtentions.cs.meta similarity index 100% rename from Assets/Scripts/VMDRecorder/UnityVMDQuaternionExtentions.cs.meta rename to Assets/Scripts/Exporters/VMDRecorder/UnityVMDQuaternionExtentions.cs.meta