fix Dispose

This commit is contained in:
ousttrue
2021-03-08 19:47:52 +09:00
parent 538f6fa919
commit 3a7fc7735e
15 changed files with 119 additions and 2112 deletions

View File

@@ -19,35 +19,6 @@ namespace UniGLTF
m_context = context;
}
// public virtual IEnumerable<UnityEngine.Object> ObjectsForSubAsset()
// {
// foreach (var x in m_context.TextureFactory.ObjectsForSubAsset())
// {
// yield return x;
// }
// foreach (var x in m_context.MaterialFactory.ObjectsForSubAsset())
// {
// yield return x;
// }
// foreach (var x in m_context.Meshes) { yield return x.Mesh; }
// foreach (var x in m_context.AnimationClips) { yield return x; }
// }
// /// <summary>
// /// Destroy assets that created ImporterContext. This function is clean up for importer error.
// /// </summary>
// public virtual void EditorDestroyRootAndAssets()
// {
// // Remove hierarchy
// if (m_context.Root != null) GameObject.DestroyImmediate(m_context.Root);
// // Remove resources. materials, textures meshes etc...
// foreach (var o in ObjectsForSubAsset())
// {
// UnityEngine.Object.DestroyImmediate(o, true);
// }
// }
public virtual UnityPath GetAssetPath(UnityPath prefabPath, UnityEngine.Object o, bool meshAsSubAsset)
{
if (o is Material)
@@ -122,6 +93,9 @@ namespace UniGLTF
prefabPath
};
// backup
var root = m_context.Root;
m_context.TransferOwnership(o =>
{
@@ -168,21 +142,13 @@ namespace UniGLTF
{
Debug.LogFormat("replace prefab: {0}", prefabPath);
var prefab = prefabPath.LoadAsset<GameObject>();
#if UNITY_2018_3_OR_NEWER
PrefabUtility.SaveAsPrefabAssetAndConnect(m_context.Root, prefabPath.Value, InteractionMode.AutomatedAction);
#else
PrefabUtility.ReplacePrefab(Root, prefab, ReplacePrefabOptions.ReplaceNameBased);
#endif
PrefabUtility.SaveAsPrefabAssetAndConnect(root, prefabPath.Value, InteractionMode.AutomatedAction);
}
else
{
Debug.LogFormat("create prefab: {0}", prefabPath);
#if UNITY_2018_3_OR_NEWER
PrefabUtility.SaveAsPrefabAssetAndConnect(m_context.Root, prefabPath.Value, InteractionMode.AutomatedAction);
#else
PrefabUtility.CreatePrefab(prefabPath.Value, Root);
#endif
PrefabUtility.SaveAsPrefabAssetAndConnect(root, prefabPath.Value, InteractionMode.AutomatedAction);
}
foreach (var x in paths)
{

View File

@@ -190,8 +190,9 @@ namespace UniGLTF
}
#endregion
#region Imported
#region Imported
public GameObject Root;
bool m_ownRoot = true;
public List<Transform> Nodes = new List<Transform>();
public List<MeshWithMaterials> Meshes = new List<MeshWithMaterials>();
@@ -252,7 +253,7 @@ namespace UniGLTF
m_materialFactory.Dispose();
m_textureFactory.Dispose();
if (Root)
if (m_ownRoot && Root != null)
{
#if VRM_DEVELOP
Debug.Log($"Destroy {Root}");
@@ -282,10 +283,10 @@ namespace UniGLTF
}
AnimationClips.Clear();
if (Root != null)
if (m_ownRoot && Root != null)
{
add(Root);
Root = null;
m_ownRoot = false;
}
}

View File

@@ -1,20 +0,0 @@
using System;
namespace UniJSON
{
public struct ActionDisposer : IDisposable
{
Action m_action;
public ActionDisposer(Action action)
{
m_action = action;
}
public void Dispose()
{
m_action();
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: ff15446e31b14ac409251c931b7c2038
timeCreated: 1531893103
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -45,13 +45,12 @@ namespace VRM.Samples
var parser = new GltfParser();
parser.ParseGlb(File.ReadAllBytes(path));
var context = new VRMImporterContext(parser);
context.Load();
context.ShowMeshes();
context.EnableUpdateWhenOffscreen();
using (new ActionDisposer(() => { GameObject.DestroyImmediate(context.Root); }))
using (var context = new VRMImporterContext(parser))
{
context.Load();
context.ShowMeshes();
context.EnableUpdateWhenOffscreen();
var importedJson = JsonParser.Parse(context.Json);
importedJson.SetValue("/extensions/VRM/exporterVersion", VRMVersion.VRM_VERSION, (f, x) => f.Value(x));
importedJson.SetValue("/asset/generator", UniGLTF.UniGLTFVersion.UNIGLTF_VERSION, (f, x) => f.Value(x));
@@ -118,16 +117,18 @@ namespace VRM.Samples
var path = AliciaPath;
var parser = new GltfParser();
parser.ParseGlb(File.ReadAllBytes(path));
var context = new VRMImporterContext(parser);
context.Load();
context.ShowMeshes();
context.EnableUpdateWhenOffscreen();
foreach (var mesh in context.Meshes)
using (var context = new VRMImporterContext(parser))
{
var src = mesh.Mesh;
var dst = src.Copy(true);
MeshTests.MeshEquals(src, dst);
context.Load();
context.ShowMeshes();
context.EnableUpdateWhenOffscreen();
foreach (var mesh in context.Meshes)
{
var src = mesh.Mesh;
var dst = src.Copy(true);
MeshTests.MeshEquals(src, dst);
}
}
}
@@ -138,28 +139,31 @@ namespace VRM.Samples
var path = AliciaPath;
var parser = new GltfParser();
parser.ParseGlb(File.ReadAllBytes(path));
var context = new VRMImporterContext(parser);
var oldJson = context.GLTF.ToJson().ParseAsJson().ToString(" ");
// 生成シリアライザでJSON化する
var f = new JsonFormatter();
GltfSerializer.Serialize(f, context.GLTF);
var parsed = f.ToString().ParseAsJson();
var newJson = parsed.ToString(" ");
using (var context = new VRMImporterContext(parser))
{
var oldJson = context.GLTF.ToJson().ParseAsJson().ToString(" ");
// File.WriteAllText("old.json", oldJson);
// File.WriteAllText("new.json", newJson);
// 生成シリアライザでJSON化する
var f = new JsonFormatter();
GltfSerializer.Serialize(f, context.GLTF);
var parsed = f.ToString().ParseAsJson();
var newJson = parsed.ToString(" ");
// 比較
Assert.AreEqual(oldJson.ParseAsJson().ToString(), newJson.ParseAsJson().ToString());
// File.WriteAllText("old.json", oldJson);
// File.WriteAllText("new.json", newJson);
// 生成デシリアライザでロードする
var ff = new JsonFormatter();
var des = GltfDeserializer.Deserialize(parsed);
ff.Clear();
GltfSerializer.Serialize(ff, des);
var desJson = ff.ToString().ParseAsJson().ToString(" ");
Assert.AreEqual(oldJson.ParseAsJson().ToString(), desJson.ParseAsJson().ToString());
// 比較
Assert.AreEqual(oldJson.ParseAsJson().ToString(), newJson.ParseAsJson().ToString());
// 生成デシリアライザでロードする
var ff = new JsonFormatter();
var des = GltfDeserializer.Deserialize(parsed);
ff.Clear();
GltfSerializer.Serialize(ff, des);
var desJson = ff.ToString().ParseAsJson().ToString(" ");
Assert.AreEqual(oldJson.ParseAsJson().ToString(), desJson.ParseAsJson().ToString());
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +0,0 @@
fileFormatVersion: 2
guid: 2f563e7bcfaebb74dbf9748df1f4824c
timeCreated: 1520832729
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -50,16 +50,18 @@ namespace VRM.Samples
var parser = new GltfParser();
parser.ParseGlb(bytes);
var context = new VRMImporterContext(parser);
using (var context = new VRMImporterContext(parser))
{
// metaを取得(todo: thumbnailテクスチャのロード)
var meta = await context.ReadMetaAsync();
Debug.LogFormat("meta: title:{0}", meta.Title);
// metaを取得(todo: thumbnailテクスチャのロード)
var meta = await context.ReadMetaAsync();
Debug.LogFormat("meta: title:{0}", meta.Title);
// ParseしたJSONをシーンオブジェクトに変換していく
await context.LoadAsync();
// ParseしたJSONをシーンオブジェクトに変換していく
await context.LoadAsync();
OnLoaded(context);
OnLoaded(context);
}
}
void OnLoaded(VRMImporterContext context)

View File

@@ -90,23 +90,24 @@ namespace VRM.Samples
var parser = new GltfParser();
parser.Parse(path, bytes);
var context = new VRMImporterContext(parser);
// metaを取得(todo: thumbnailテクスチャのロード)
var meta = await context.ReadMetaAsync();
Debug.LogFormat("meta: title:{0}", meta.Title);
// ParseしたJSONをシーンオブジェクトに変換していく
if (m_loadAsync)
using (var context = new VRMImporterContext(parser))
{
await context.LoadAsync();
}
else
{
context.Load();
}
// metaを取得(todo: thumbnailテクスチャのロード)
var meta = await context.ReadMetaAsync();
Debug.LogFormat("meta: title:{0}", meta.Title);
OnLoaded(context);
// ParseしたJSONをシーンオブジェクトに変換していく
if (m_loadAsync)
{
await context.LoadAsync();
}
else
{
context.Load();
}
OnLoaded(context);
}
}
/// <summary>
@@ -167,10 +168,12 @@ namespace VRM.Samples
void OnLoaded(VRMImporterContext context)
{
var root = context.Root;
root.transform.SetParent(transform, false);
//メッシュを表示します
context.ShowMeshes();
context.DisposeOnGameObjectDestroyed();
// add motion
var humanPoseTransfer = root.AddComponent<UniHumanoid.HumanPoseTransfer>();

View File

@@ -1,188 +0,0 @@
#pragma warning disable 0414
using System;
using System.IO;
using UnityEngine;
#if (NET_4_6 && UNITY_2017_1_OR_NEWER)
using System.Threading.Tasks;
#endif
namespace VRM.Samples
{
public class VRMRuntimeLoaderNet4 : MonoBehaviour
{
[SerializeField, Header("GUI")]
CanvasManager m_canvas;
[SerializeField]
LookTarget m_faceCamera;
[SerializeField, Header("loader")]
UniHumanoid.HumanPoseTransfer m_source;
[SerializeField]
UniHumanoid.HumanPoseTransfer m_target;
[SerializeField, Header("runtime")]
VRMFirstPerson m_firstPerson;
#if (NET_4_6 && UNITY_2017_1_OR_NEWER && !UNITY_WEBGL)
VRMBlendShapeProxy m_blendShape;
void SetupTarget()
{
if (m_target != null)
{
m_target.Source = m_source;
m_target.SourceType = UniHumanoid.HumanPoseTransfer.HumanPoseTransferSourceType.HumanPoseTransfer;
m_blendShape = m_target.GetComponent<VRMBlendShapeProxy>();
m_firstPerson = m_target.GetComponent<VRMFirstPerson>();
var animator = m_target.GetComponent<Animator>();
if (animator != null)
{
m_firstPerson.Setup();
if (m_faceCamera != null)
{
m_faceCamera.Target = animator.GetBoneTransform(HumanBodyBones.Head);
}
}
}
}
private void Awake()
{
SetupTarget();
}
private void Start()
{
if (m_canvas == null)
{
Debug.LogWarning("no canvas");
return;
}
m_canvas.LoadVRMButton.onClick.AddListener(LoadVRMClicked);
m_canvas.LoadBVHButton.onClick.AddListener(LoadBVHClicked);
}
// Byte列を得る
async static Task<Byte[]> ReadBytesAsync(string path)
{
return File.ReadAllBytes(path);
}
async static Task<VRMImporterContext> LoadAsync(Byte[] bytes)
{
var context = new VRMImporterContext();
// GLB形式でJSONを取得しParseします
context.ParseGlb(bytes);
// ParseしたJSONをシーンオブジェクトに変換していく
await context.LoadAsyncTask();
return context;
}
/// <summary>
/// Taskで非同期にロードする例
/// </summary>
async void LoadVRMClicked()
{
#if UNITY_STANDALONE_WIN
var path = FileDialogForWindows.FileDialog("open VRM", ".vrm");
#elif UNITY_EDITOR
var path = UnityEditor.EditorUtility.OpenFilePanel("Open VRM", "", "vrm");
#else
var path = Application.dataPath + "/default.vrm";
#endif
if (string.IsNullOrEmpty(path))
{
return;
}
var context = new VRMImporterContext();
var bytes = await ReadBytesAsync(path);
// GLB形式でJSONを取得しParseします
context.ParseGlb(bytes);
// metaを取得(todo: thumbnailテクスチャのロード)
var meta = context.ReadMeta();
Debug.LogFormat("meta: title:{0}", meta.Title);
// ParseしたJSONをシーンオブジェクトに変換していく
var now = Time.time;
await context.LoadAsyncTask();
var delta = Time.time - now;
Debug.LogFormat("LoadVrmAsync {0:0.0} seconds", delta);
OnLoaded(context);
}
void LoadBVHClicked()
{
#if UNITY_STANDALONE_WIN
var path = FileDialogForWindows.FileDialog("open BVH", ".bvh");
if (!string.IsNullOrEmpty(path))
{
LoadBvh(path);
}
#elif UNITY_EDITOR
var path = UnityEditor.EditorUtility.OpenFilePanel("Open BVH", "", "bvh");
if (!string.IsNullOrEmpty(path))
{
LoadBvh(path);
}
#else
LoadBvh(Application.dataPath + "/default.bvh");
#endif
}
void OnLoaded(VRMImporterContext context)
{
var root = context.Root;
root.transform.SetParent(transform, false);
//メッシュを表示します
context.ShowMeshes();
// add motion
var humanPoseTransfer = root.AddComponent<UniHumanoid.HumanPoseTransfer>();
if (m_target != null)
{
GameObject.Destroy(m_target.gameObject);
}
m_target = humanPoseTransfer;
SetupTarget();
}
void LoadBvh(string path)
{
Debug.LogFormat("ImportBvh: {0}", path);
var context = new UniHumanoid.BvhImporterContext();
context.Parse(path);
context.Load();
if (m_source != null)
{
GameObject.Destroy(m_source.gameObject);
}
m_source = context.Root.GetComponent<UniHumanoid.HumanPoseTransfer>();
SetupTarget();
}
#endif
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 649886f2803ade846a93be89f73e35c7
timeCreated: 1517899576
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -314,15 +314,15 @@ namespace VRM.Samples
var parser = new GltfParser();
parser.ParseGlb(file);
var context = new VRMImporterContext(parser);
await m_texts.UpdateMetaAsync(context);
await context.LoadAsync();
context.DisposeOnGameObjectDestroyed();
context.ShowMeshes();
context.EnableUpdateWhenOffscreen();
context.ShowMeshes();
SetModel(context.Root);
using (var context = new VRMImporterContext(parser))
{
await m_texts.UpdateMetaAsync(context);
await context.LoadAsync();
context.EnableUpdateWhenOffscreen();
context.ShowMeshes();
context.DisposeOnGameObjectDestroyed();
SetModel(context.Root);
}
break;
}
@@ -334,10 +334,9 @@ namespace VRM.Samples
var context = new UniGLTF.ImporterContext(parser);
context.Load();
context.DisposeOnGameObjectDestroyed();
context.ShowMeshes();
context.EnableUpdateWhenOffscreen();
context.ShowMeshes();
context.DisposeOnGameObjectDestroyed();
SetModel(context.Root);
break;
}
@@ -350,10 +349,9 @@ namespace VRM.Samples
var context = new UniGLTF.ImporterContext(parser);
context.Load();
context.DisposeOnGameObjectDestroyed();
context.ShowMeshes();
context.EnableUpdateWhenOffscreen();
context.ShowMeshes();
context.DisposeOnGameObjectDestroyed();
SetModel(context.Root);
break;
}

View File

@@ -22,11 +22,15 @@ namespace VRM
// load into scene
var parser = new GltfParser();
parser.ParsePath(path);
var context = new VRMImporterContext(parser);
context.Load();
context.ShowMeshes();
context.EnableUpdateWhenOffscreen();
Selection.activeGameObject = context.Root;
using (var context = new VRMImporterContext(parser))
{
context.Load();
context.EnableUpdateWhenOffscreen();
context.ShowMeshes();
context.DisposeOnGameObjectDestroyed();
Selection.activeGameObject = context.Root;
}
}
else
{
@@ -52,18 +56,24 @@ namespace VRM
var prefabPath = UnityPath.FromUnityPath(assetPath);
var parser = new GltfParser();
parser.ParseGlb(File.ReadAllBytes(path));
var context = new VRMImporterContext(parser);
var editor = new VRMEditorImporterContext(context);
editor.ExtractImages(prefabPath);
using (var context = new VRMImporterContext(parser))
{
var editor = new VRMEditorImporterContext(context);
editor.ExtractImages(prefabPath);
}
EditorApplication.delayCall += () =>
{
//
// after textures imported
//
context.Load();
editor.SaveAsAsset(prefabPath);
context.Dispose();
using (var context = new VRMImporterContext(parser))
{
var editor = new VRMEditorImporterContext(context);
context.Load();
editor.SaveAsAsset(prefabPath);
}
};
}
}

View File

@@ -59,18 +59,24 @@ namespace VRM
var texture = await UniGLTF.AssetTextureLoader.LoadTaskAsync(assetPath, parser.GLTF, textureIndex);
return new TextureLoadInfo(texture, used, false);
};
var context = new VRMImporterContext(parser, textureLoader);
var editor = new VRMEditorImporterContext(context);
editor.ExtractImages(prefabPath);
using (var context = new VRMImporterContext(parser, textureLoader))
{
var editor = new VRMEditorImporterContext(context);
editor.ExtractImages(prefabPath);
}
EditorApplication.delayCall += () =>
{
//
// after textures imported
//
context.Load();
editor.SaveAsAsset(prefabPath);
context.Dispose();
using (var context = new VRMImporterContext(parser, textureLoader))
{
var editor = new VRMEditorImporterContext(context);
context.Load();
editor.SaveAsAsset(prefabPath);
}
};
}
}

View File

@@ -306,8 +306,6 @@ namespace VRM
public override void TransferOwnership(Action<UnityEngine.Object> add)
{
base.TransferOwnership(add);
// VRM 固有のリソース(ScriptableObject)
add(HumanoidAvatar);
HumanoidAvatar = null;
@@ -326,6 +324,8 @@ namespace VRM
add(BlendShapeAvatar);
BlendShapeAvatar = null;
base.TransferOwnership(add);
}
}
}