public async void Setup(SyncObject obj) { // TODO: dynamic model change handling if (!obj.HasField("model") || !(obj.GetField("model") is BlobHandle)) { // TODO: obj.WriteErrorLog("Model", $"This object has no model field or not a blob handle. Ignoring."); return; } BlobHandle handle = (BlobHandle)obj.GetField("model"); Blob blob = await obj.Node.ReadBlob(handle); obj.WriteDebugLog("Model", $"Blob {handle} loaded"); // Because UniGLTF.ImporterContext is the parent class of VRMImporterContext, // ( https://github.com/vrm-c/UniVRM/blob/3b68eb7f99bfe78ea9c83ea75511282ef1782f1a/Assets/VRM/UniVRM/Scripts/Format/VRMImporterContext.cs#L11 ) // loading procedure is probably almost same (See PlyayerAvatar.cs for VRM loading). // https://github.com/vrm-c/UniVRM/blob/3b68eb7f99bfe78ea9c83ea75511282ef1782f1a/Assets/VRM/UniGLTF/Editor/Tests/UniGLTFTests.cs#L46 ctx = new UniGLTF.ImporterContext(); // ParseGlb parses GLB file. // https://github.com/vrm-c/UniVRM/blob/3b68eb7f99bfe78ea9c83ea75511282ef1782f1a/Assets/VRM/UniGLTF/Scripts/IO/ImporterContext.cs#L239 // Currently, only GLB (glTF binary format) is supported because it is self-contained ctx.ParseGlb(blob.Data); ctx.Root = gameObject; await ctx.LoadAsyncTask(); // UniGLTF also has ShowMeshes https://github.com/ousttrue/UniGLTF/wiki/Rutime-API#import ctx.ShowMeshes(); obj.WriteDebugLog("Model", "Model load completed"); LoadComplete?.Invoke(this); }
public static ImporterContext Load(string path) { var context = new ImporterContext(); context.Load(path); context.ShowMeshes(); context.EnableUpdateWhenOffscreen(); return(context); }
public static void ImportMenu() { var path = UnityEditor.EditorUtility.OpenFilePanel("open gltf", "", "gltf,glb"); if (!string.IsNullOrEmpty(path)) { Debug.Log(path); var context = new ImporterContext { Path = path, }; var bytes = File.ReadAllBytes(path); var ext = Path.GetExtension(path).ToLower(); switch (ext) { case ".gltf": { context.ParseJson <glTF>(Encoding.UTF8.GetString(bytes), new FileSystemStorage(Path.GetDirectoryName(path))); gltfImporter.Import <glTF>(context); context.Root.name = Path.GetFileNameWithoutExtension(path); context.ShowMeshes(); Selection.activeGameObject = context.Root; } break; case ".glb": { context.ParseGlb <glTF>(bytes); gltfImporter.Import <glTF>(context); context.Root.name = Path.GetFileNameWithoutExtension(path); context.ShowMeshes(); Selection.activeGameObject = context.Root; } break; default: Debug.LogWarningFormat("unknown ext: {0}", path); break; } } }
IEnumerator Start() { Debug.LogFormat("get {0}", m_url); var www = new WWW(m_url); yield return(www); var bytes = www.bytes; if (!string.IsNullOrEmpty(www.error)) { Debug.LogWarningFormat("fail to download: {0}", www.error); yield break; } Debug.LogFormat("downloaded {0} bytes", bytes.Length); var task = CoroutineUtil.RunOnThread(() => Zip.ZipArchiveStorage.Parse(bytes)); yield return(task); if (task.Error != null) { throw task.Error; } var zipArchive = task.Result; Debug.LogFormat("done {0}", zipArchive); var gltf = zipArchive.Entries.FirstOrDefault(x => x.FileName.ToLower().EndsWith(".gltf")); if (gltf == null) { Debug.LogWarning("no gltf in archive"); yield break; } #if false var json = zipArchive.ExtractToString(gltf, Encoding.UTF8); #else var jsonBytes = zipArchive.Extract(gltf); var json = Encoding.UTF8.GetString(jsonBytes); #endif Debug.LogFormat("gltf json: {0}", json); var context = new ImporterContext(); context.ParseJson(json, zipArchive); context.Load(); context.ShowMeshes(); }
public static void LoadVrmAsync(string path, Byte[] bytes, Action <GameObject> onLoaded, Action <Exception> onError = null, bool show = true) { var context = new ImporterContext(); context.Parse(path, bytes); context.LoadAsync(_ => { if (show) { context.ShowMeshes(); } onLoaded(context.Root); }, onError); }
/// <summary> /// glb をパースして、UnityObject化、さらにAsset化する /// </summary> /// <param name="scriptedImporter"></param> /// <param name="context"></param> /// <param name="reverseAxis"></param> public static void Import(ScriptedImporter scriptedImporter, AssetImportContext context, Axises reverseAxis) { #if VRM_DEVELOP Debug.Log("OnImportAsset to " + scriptedImporter.assetPath); #endif // // Parse(parse glb, parser gltf json) // var parser = new GltfParser(); parser.ParsePath(scriptedImporter.assetPath); // // Import(create unity objects) // var externalObjectMap = scriptedImporter.GetExternalObjectMap().Select(kv => (kv.Value.name, kv.Value)).ToArray(); var externalTextures = EnumerateTexturesFromUri(externalObjectMap, parser, UnityPath.FromUnityPath(scriptedImporter.assetPath).Parent).ToArray(); using (var loaded = new ImporterContext(parser, null, externalObjectMap.Concat(externalTextures))) { // settings TextureImporters foreach (var textureInfo in GltfTextureEnumerator.Enumerate(parser.GLTF)) { TextureImporterConfigurator.Configure(textureInfo, loaded.TextureFactory.ExternalMap); } loaded.InvertAxis = reverseAxis; loaded.Load(); loaded.ShowMeshes(); loaded.TransferOwnership(o => { #if VRM_DEVELOP Debug.Log($"[{o.GetType().Name}] {o.name} will not destroy"); #endif context.AddObjectToAsset(o.name, o); if (o is GameObject) { // Root GameObject is main object context.SetMainObject(loaded.Root); } return(true); }); } }
GameObject Load(string path) { var bytes = File.ReadAllBytes(path); Debug.LogFormat("[OnClick] {0}", path); var context = new ImporterContext(); var ext = Path.GetExtension(path).ToLower(); switch (ext) { case ".gltf": context.ParseJson(Encoding.UTF8.GetString(bytes), new FileSystemStorage(Path.GetDirectoryName(path))); break; case ".zip": { var zipArchive = Zip.ZipArchiveStorage.Parse(bytes); var gltf = zipArchive.Entries.FirstOrDefault(x => x.FileName.ToLower().EndsWith(".gltf")); if (gltf == null) { throw new Exception("no gltf in archive"); } var jsonBytes = zipArchive.Extract(gltf); var json = Encoding.UTF8.GetString(jsonBytes); context.ParseJson(json, zipArchive); } break; case ".glb": context.ParseGlb(bytes); break; default: throw new NotImplementedException(); } context.Load(); context.Root.name = Path.GetFileNameWithoutExtension(path); context.ShowMeshes(); return(context.Root); }
public static void ImportMenu() { var path = EditorUtility.OpenFilePanel("open gltf", "", "gltf,glb"); if (string.IsNullOrEmpty(path)) { return; } if (Application.isPlaying) { // // load into scene // var parser = new GltfParser(); parser.ParsePath(path); var context = new ImporterContext(parser); context.Load(); context.ShowMeshes(); Selection.activeGameObject = context.Root; } else { // // save as asset // if (path.StartsWithUnityAssetPath()) { Debug.LogWarningFormat("disallow import from folder under the Assets"); return; } var assetPath = EditorUtility.SaveFilePanel("save prefab", "Assets", Path.GetFileNameWithoutExtension(path), "prefab"); if (string.IsNullOrEmpty(path)) { return; } // import as asset gltfAssetPostprocessor.ImportAsset(path, Path.GetExtension(path).ToLower(), UnityPath.FromFullpath(assetPath)); } }
public override void OnImportAsset(AssetImportContext ctx) { Debug.Log("OnImportAsset to " + ctx.assetPath); try { // Parse var parser = new GltfParser(); parser.ParsePath(ctx.assetPath); // Build Unity Model var externalObjectMap = GetExternalObjectMap() .Select(kv => (kv.Key.name, kv.Value)) ; var context = new ImporterContext(parser, externalObjectMap); context.InvertAxis = m_reverseAxis; context.Load(); context.ShowMeshes(); // Texture foreach (var info in context.TextureFactory.Textures) { if (!info.IsUsed) { continue; } if (!info.IsExternal) { var texture = info.Texture; ctx.AddObjectToAsset(texture.name, texture); } } // Material foreach (var info in context.MaterialFactory.Materials) { if (!info.UseExternal) { var material = info.Asset; ctx.AddObjectToAsset(material.name, material); } } // Mesh foreach (var mesh in context.Meshes.Select(x => x.Mesh)) { ctx.AddObjectToAsset(mesh.name, mesh); } // Animation foreach (var clip in context.AnimationClips) { ctx.AddObjectToAsset(clip.name, clip); } // Root ctx.AddObjectToAsset(context.Root.name, context.Root); ctx.SetMainObject(context.Root); } catch (System.Exception ex) { Debug.LogError(ex); } }
async void LoadModelAsync(string path) { if (!File.Exists(path)) { return; } Debug.LogFormat("{0}", path); var ext = Path.GetExtension(path).ToLower(); switch (ext) { case ".vrm": { var file = File.ReadAllBytes(path); var parser = new GltfParser(); parser.ParseGlb(file); using (var context = new VRMImporterContext(parser)) { await m_texts.UpdateMetaAsync(context); await context.LoadAsync(); context.EnableUpdateWhenOffscreen(); context.ShowMeshes(); context.DisposeOnGameObjectDestroyed(); SetModel(context.Root); } break; } case ".glb": { var file = File.ReadAllBytes(path); var parser = new GltfParser(); parser.ParseGlb(file); var context = new UniGLTF.ImporterContext(parser); context.Load(); context.EnableUpdateWhenOffscreen(); context.ShowMeshes(); context.DisposeOnGameObjectDestroyed(); SetModel(context.Root); break; } case ".gltf": case ".zip": { var parser = new GltfParser(); parser.ParsePath(path); var context = new UniGLTF.ImporterContext(parser); context.Load(); context.EnableUpdateWhenOffscreen(); context.ShowMeshes(); context.DisposeOnGameObjectDestroyed(); SetModel(context.Root); break; } default: Debug.LogWarningFormat("unknown file type: {0}", path); break; } }
public static void Load(ImporterContext context) { context.Load(); context.ShowMeshes(); context.EnableUpdateWhenOffscreen(); }
void LoadModel(string path) { if (!File.Exists(path)) { return; } Debug.LogFormat("{0}", path); var ext = Path.GetExtension(path).ToLower(); switch (ext) { case ".vrm": { var parser = new UniGLTF.GltfParser(); parser.ParsePath(path); using (var loader = new RuntimeUnityBuilder(parser)) { loader.Load(); loader.ShowMeshes(); loader.EnableUpdateWhenOffscreen(); var destroyer = loader.DisposeOnGameObjectDestroyed(); SetModel(destroyer.gameObject); } break; } case ".glb": { var file = File.ReadAllBytes(path); var parser = new GltfParser(); parser.ParseGlb(file); using (var loader = new UniGLTF.ImporterContext(parser)) { loader.Load(); loader.ShowMeshes(); loader.EnableUpdateWhenOffscreen(); loader.ShowMeshes(); var destroyer = loader.DisposeOnGameObjectDestroyed(); SetModel(destroyer.gameObject); } break; } case ".gltf": case ".zip": { var parser = new GltfParser(); parser.ParsePath(path); using (var loader = new UniGLTF.ImporterContext(parser)) { loader.Load(); loader.ShowMeshes(); loader.EnableUpdateWhenOffscreen(); loader.ShowMeshes(); var destroyer = loader.DisposeOnGameObjectDestroyed(); SetModel(destroyer.gameObject); } break; } default: Debug.LogWarningFormat("unknown file type: {0}", path); break; } }
public void SaveAsAsset(UnityPath prefabPath, bool meshAsSubAsset = false) { m_context.ShowMeshes(); //var prefabPath = PrefabPath; if (prefabPath.IsFileExists) { // clear SubAssets foreach (var x in prefabPath.GetSubAssets().Where(x => !(x is GameObject) && !(x is Component))) { GameObject.DestroyImmediate(x, true); } } // // save sub assets // var paths = new List <UnityPath>() { prefabPath }; foreach (var o in ObjectsForSubAsset()) { if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(o))) { // already exists continue; } var assetPath = GetAssetPath(prefabPath, o, meshAsSubAsset); if (!assetPath.IsNull) { if (assetPath.IsFileExists) { if (AvoidOverwriteAndLoad(assetPath, o)) { // 上書きせずに既存のアセットからロードして置き換えた continue; } } // アセットとして書き込む assetPath.Parent.EnsureFolder(); assetPath.CreateAsset(o); paths.Add(assetPath); } else { // save as subasset prefabPath.AddObjectToAsset(o); } } // Create or update Main Asset if (prefabPath.IsFileExists) { 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 } 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 } foreach (var x in paths) { x.ImportAsset(); } }
void LoadModel(string path) { if (!File.Exists(path)) { return; } Debug.LogFormat("{0}", path); var ext = Path.GetExtension(path).ToLower(); switch (ext) { case ".vrm": { // var context = new ImporterContext(); var file = File.ReadAllBytes(path); // context.ParseGlb(file); // context.Load(); // context.ShowMeshes(); // context.EnableUpdateWhenOffscreen(); // context.ShowMeshes(); var model = UniVRM10.VrmLoader.CreateVrmModel(file, new FileInfo(path)); // UniVRM-0.XXのコンポーネントを構築する var assets = UniVRM10.RuntimeUnityBuilder.ToUnityAsset(model, showMesh: false); // showRenderer = false のときに後で表示する例 foreach (var renderer in assets.Renderers) { renderer.enabled = true; } UniVRM10.ComponentBuilder.Build10(model, assets); SetModel(assets.Root); break; } case ".glb": { var file = File.ReadAllBytes(path); var parser = new GltfParser(); parser.ParseGlb(file); var context = new UniGLTF.ImporterContext(parser); context.Load(); context.ShowMeshes(); context.EnableUpdateWhenOffscreen(); context.ShowMeshes(); SetModel(context.Root); break; } case ".gltf": case ".zip": { var parser = new GltfParser(); parser.ParsePath(path); var context = new UniGLTF.ImporterContext(parser); context.Load(); context.ShowMeshes(); context.EnableUpdateWhenOffscreen(); context.ShowMeshes(); SetModel(context.Root); break; } default: Debug.LogWarningFormat("unknown file type: {0}", path); break; } }