Exemple #1
0
//         private void RestoreOlderVersionValues()
//         {
//             var parsed = UniJSON.JsonParser.Parse(json);
//             for (int i = 0; i < gltf.images.Count; ++i)
//             {
//                 if (string.IsNullOrEmpty(gltf.images[i].name))
//                 {
//                     try
//                     {
//                         var extraName = parsed["images"][i]["extra"]["name"].Value.GetString();
//                         if (!string.IsNullOrEmpty(extraName))
//                         {
//                             //Debug.LogFormat("restore texturename: {0}", extraName);
//                             gltf.images[i].name = extraName;
//                         }
//                     }
//                     catch (Exception)
//                     {
//                         // do nothing
//                     }
//                 }
//             }
//             for (int i = 0; i < gltf.meshes.Count; ++i)
//             {
//                 var mesh = gltf.meshes[i];
//                 try
//                 {
//                     for (int j = 0; j < mesh.primitives.Count; ++j)
//                     {
//                         var primitive = mesh.primitives[j];
//                         for (int k = 0; k < primitive.targets.Count; ++k)
//                         {
//                             var extraName = parsed["meshes"][i]["primitives"][j]["targets"][k]["extra"]["name"].Value.GetString();
//                             //Debug.LogFormat("restore morphName: {0}", extraName);
//                             primitive.extras.targetNames.Add(extraName);
//                         }
//                     }
//                 }
//                 catch (Exception)
//                 {
//                     // do nothing
//                 }
//             }
// #if false
//             for (int i = 0; i < GLTF.nodes.Count; ++i)
//             {
//                 var node = GLTF.nodes[i];
//                 try
//                 {
//                     var extra = parsed["nodes"][i]["extra"]["skinRootBone"].AsInt;
//                     //Debug.LogFormat("restore extra: {0}", extra);
//                     //node.extras.skinRootBone = extra;
//                 }
//                 catch (Exception)
//                 {
//                     // do nothing
//                 }
//             }
// #endif
//         }
        #endregion

        public void CreateTextureItems(UnityPath imageBaseDir = default(UnityPath))
        {
//            Debug.Log("create texture items" + _textures.Count);
            if (_textures.Any())
            {
                return;
            }

            for (int i = 0; i < gltf.textures.Count; ++i)
            {
                var image = gltf.GetImageFromTextureIndex(i);

                TextureItem item = null;
#if UNITY_EDITOR
                if (imageBaseDir.isUnderAssetsFolder &&
                    !string.IsNullOrEmpty(image.uri) &&
                    !image.uri.StartsWith("data:")
                    )
                {
                    ///
                    /// required SaveTexturesAsPng or SetTextureBaseDir
                    ///
                    var assetPath   = imageBaseDir.Child(image.uri);
                    var textureName = !string.IsNullOrEmpty(image.name) ? image.name : Path.GetFileNameWithoutExtension(image.uri);
                    item = new TextureItem(i, assetPath, textureName);
                }
                else
#endif
                {
                    item = new TextureItem(i);
                }

                AddTexture(item);
            }
        }
Exemple #2
0
 protected static UnityPath GetAssetPath(UnityPath prefabPath, UnityEngine.Object o)
 {
     if (o is Material)
     {
         var materialDir  = prefabPath.GetAssetFolder(".Materials");
         var materialPath = materialDir.Child(o.name.EscapeFilePath() + ".asset");
         return(materialPath);
     }
     else if (o is Texture2D)
     {
         var textureDir  = prefabPath.GetAssetFolder(".Textures");
         var texturePath = textureDir.Child(o.name.EscapeFilePath() + ".asset");
         return(texturePath);
     }
     else if (o is Mesh && !MeshAsSubAsset)
     {
         var meshDir  = prefabPath.GetAssetFolder(".Meshes");
         var meshPath = meshDir.Child(o.name.EscapeFilePath() + ".asset");
         return(meshPath);
     }
     else
     {
         return(default(UnityPath));
     }
 }
Exemple #3
0
        static void ImportDelayed(GLTFImporter context, UnityPath prefabPath)
        {
            EditorApplication.delayCall += () =>
            {
                //
                // After textures imported(To ensure TextureImporter be accessible).
                //
                // try
                // {

                var t = Save(context, prefabPath);
                // }
                // catch (UniGLTFNotSupportedException ex)
                // {
                //     Debug.LogWarningFormat($"{src}: {ex.Message}");
                //     context.EditorDestroyRootAndAssets();
                // }
                // catch (Exception ex)
                // {
                //     Debug.LogErrorFormat("import error: {0}", src);
                //     Debug.LogErrorFormat("{0}", ex);
                //     context.EditorDestroyRootAndAssets();
                // }
            };
        }
Exemple #4
0
        private static async Task Save(GLTFImporter context, UnityPath path)
        {
            await context.Load(context.storage, p => Debug.Log(p));

            context.ShowMeshes();
            await SaveAsAsset(context, path);

            context.EditorDestroyRoot();
        }
        public static void IntegrateSelected()
        {
            var go = Selection.activeObject as GameObject;
            var meshWithMaterials = Integrate(go.transform);

            // save as asset
            var assetPath = "";

#if UNITY_2018_2_OR_NEWER
            var prefab = PrefabUtility.GetCorrespondingObjectFromSource(go);
#else
            var prefab = PrefabUtility.GetPrefabParent(go);
#endif
            if (prefab != null)
            {
                var prefabPath = AssetDatabase.GetAssetPath(prefab);
                assetPath = string.Format("{0}/{1}_{2}{3}",
                                          Path.GetDirectoryName(prefabPath),
                                          Path.GetFileNameWithoutExtension(prefabPath),
                                          go.name,
                                          ASSET_SUFFIX
                                          );
            }
            else
            {
                var path = EditorUtility.SaveFilePanel(
                    "Save mesh",
                    "Assets",
                    go.name + ".asset",
                    "asset");
                if (string.IsNullOrEmpty(path))
                {
                    return;
                }
                assetPath = UnityPath.FromFullpath(path).value;
            }

            assetPath = AssetDatabase.GenerateUniqueAssetPath(assetPath);
            Debug.LogFormat("CreateAsset: {0}", assetPath);
            AssetDatabase.CreateAsset(meshWithMaterials.Mesh, assetPath);

            // add component
            var meshObject = new GameObject(go.name + ".integrated");
            if (go.transform.parent != null)
            {
                meshObject.transform.SetParent(go.transform.parent, false);
            }
            meshObject.transform.localPosition = go.transform.localPosition;
            meshObject.transform.localRotation = go.transform.localRotation;
            meshObject.transform.localScale    = go.transform.localScale;

            var filter = meshObject.AddComponent <MeshFilter>();
            filter.sharedMesh = meshWithMaterials.Mesh;
            var renderer = meshObject.AddComponent <MeshRenderer>();
            renderer.sharedMaterials = meshWithMaterials.Materials;
        }
Exemple #6
0
        public static void ImportAsset(string src, string ext, UnityPath prefabPath)
        {
            if (!prefabPath.isUnderAssetsFolder)
            {
                Debug.LogWarningFormat("out of asset path: {0}", prefabPath);
                return;
            }
            var context = new GLTFImporter();

            context.Parse(src);

            // Extract textures to assets folder
            ExtranctImages(context, prefabPath);

            ImportDelayed(context, prefabPath);
        }
Exemple #7
0
        /// <summary>
        /// Extract images from glb or gltf out of Assets folder.
        /// </summary>
        /// <param name="prefabPath"></param>
        public static void ExtranctImages(GLTFImporter context, UnityPath prefabPath)
        {
            var prefabParentDir = prefabPath.parent;

            // glb buffer
            var folder = prefabPath.GetAssetFolder(".Textures");

            //
            // https://answers.unity.com/questions/647615/how-to-update-import-settings-for-newly-created-as.html
            //
            int created = 0;

            //for (int i = 0; i < GLTF.textures.Count; ++i)
            for (int i = 0; i < context.gltf.images.Count; ++i)
            {
                folder.EnsureFolder();

                //var x = GLTF.textures[i];
                var image = context.gltf.images[i];
                var src   = context.storage.GetPath(image.uri);
                if (UnityPath.FromFullpath(src).isUnderAssetsFolder)
                {
                    // asset is exists.
                }
                else
                {
                    string textureName;
                    var    byteSegment = context.gltf.GetImageBytes(context.storage, i, out textureName, out var url);

                    // path
                    var dst = folder.Child(textureName + image.GetExt());
                    File.WriteAllBytes(dst.fullPath, byteSegment.ToArray());
                    dst.ImportAsset();

                    // make relative path from PrefabParentDir
                    image.uri = dst.value.Substring(prefabParentDir.value.Length + 1);
                    ++created;
                }
            }

            if (created > 0)
            {
                AssetDatabase.Refresh();
            }

            context.CreateTextureItems(prefabParentDir);
        }
Exemple #8
0
 static void OnPostprocessAllAssets(string[] importedAssets,
                                    string[] deletedAssets,
                                    string[] movedAssets,
                                    string[] movedFromAssetPaths)
 {
     foreach (string path in importedAssets)
     {
         var ext = Path.GetExtension(path).ToLower();
         switch (ext)
         {
         case ".gltf":
         case ".glb":
         {
             var gltfPath   = UnityPath.FromUnityPath(path);
             var prefabPath = gltfPath.parent.Child(gltfPath.fileNameWithoutExtension + ".prefab");
             ImportAsset(UnityPath.FromUnityPath(path).fullPath, ext, prefabPath);
             break;
         }
         }
     }
 }
Exemple #9
0
        static void CopySRGBWrite(bool isSRGB)
        {
            var src         = Selection.activeObject as Texture;
            var texturePath = UnityPath.FromAsset(src);

            var path = EditorUtility.SaveFilePanel("save prefab", "Assets",
                                                   Path.GetFileNameWithoutExtension(AddPath(texturePath.FullPath, ".sRGB")), "prefab");
            var assetPath = UnityPath.FromFullpath(path);

            if (!assetPath.IsUnderAssetsFolder)
            {
                return;
            }
            Debug.LogFormat("[CopySRGBWrite] {0} => {1}", texturePath, assetPath);

            var renderTexture = new RenderTexture(src.width, src.height, 0,
                                                  RenderTextureFormat.ARGB32,
                                                  RenderTextureReadWrite.sRGB);

            using (var scope = new ColorSpaceScope(isSRGB))
            {
                Graphics.Blit(src, renderTexture);
            }

            var dst = new Texture2D(src.width, src.height, TextureFormat.ARGB32, false,
                                    RenderTextureReadWrite.sRGB == RenderTextureReadWrite.Linear);

            dst.ReadPixels(new Rect(0, 0, src.width, src.height), 0, 0);
            dst.Apply();

            RenderTexture.active = null;

            assetPath.CreateAsset(dst);

            GameObject.DestroyImmediate(renderTexture);
        }
Exemple #10
0
        public void UnityPathTest()
        {
            var root = UnityPath.FromUnityPath(".");

            Assert.IsFalse(root.isNull);
            Assert.IsFalse(root.isUnderAssetsFolder);
            Assert.AreEqual(UnityPath.FromUnityPath("."), root);

            var assets = UnityPath.FromUnityPath("Assets");

            Assert.IsFalse(assets.isNull);
            Assert.IsTrue(assets.isUnderAssetsFolder);

            var rootChild = root.Child("Assets");

            Assert.AreEqual(assets, rootChild);

            var assetsChild = assets.Child("Hoge");
            var hoge        = UnityPath.FromUnityPath("Assets/Hoge");

            Assert.AreEqual(assetsChild, hoge);

            //var children = root.TravserseDir().ToArray();
        }
Exemple #11
0
        public static void ImportMenu()
        {
            var path = EditorUtility.OpenFilePanel("open gltf", "", "gltf,glb,zip");

            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            if (Application.isPlaying)
            {
                //
                // load into scene
                //
                var context = new GLTFImporter();
                //context.Load(path);
                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));
            }
        }
Exemple #12
0
        public static async Task SaveAsAsset(GLTFImporter context, UnityPath prefabPath)
        {
            //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 context.ObjectsForSubAsset())
            {
                if (o == null)
                {
                    continue;
                }

                var assetPath = GetAssetPath(prefabPath, o);
                if (!assetPath.isNull)
                {
                    if (assetPath.isFileExists)
                    {
                        if (!IsOverwrite(o))
                        {
                            // 上書きしない
                            Debug.LogWarningFormat("already exists. skip {0}", assetPath);
                            continue;
                        }
                    }
                    assetPath.parent.EnsureFolder();
                    assetPath.CreateAsset(o);
                    paths.Add(assetPath);
                }
                else
                {
                    // save as subasset
                    prefabPath.AddObjectToAsset(o);
                }
            }
            await Task.Yield();

            // Create or upate Main Asset
            // if (prefabPath.isFileExists)
            // {
            //     Debug.LogFormat("replace prefab: {0}", prefabPath);
            //     //var prefab = prefabPath.LoadAsset<GameObject>();
            // }
            // else
            // {
            //     Debug.LogFormat("create prefab: {0}", prefabPath);
            //     PrefabUtility.SaveAsPrefabAsset(context.root, prefabPath.value);//.CreatePrefab(prefabPath.Value, context.root);
            // }
            PrefabUtility.SaveAsPrefabAssetAndConnect(context.root, prefabPath.value, InteractionMode.AutomatedAction);    //.ReplacePrefab(context.root, prefab, ReplacePrefabOptions.ReplaceNameBased);
            await Task.Yield();

            AssetDatabase.Refresh();
            // foreach (var x in paths)
            // {
            //     x.ImportAsset();
            // }
            await Task.Yield();
        }
Exemple #13
0
 /// <summary>
 /// Texture from asset
 /// </summary>
 /// <param name="index"></param>
 /// <param name="assetPath"></param>
 /// <param name="textureName"></param>
 public TextureItem(int index, UnityPath assetPath, string textureName)
 {
     _textureIndex  = index;
     isAsset        = true;
     _textureLoader = new AssetTextureLoader(assetPath, textureName);
 }
Exemple #14
0
 public AssetTextureLoader(UnityPath assetPath, string _)
 {
     _assetPath = assetPath;
 }