/// <summary>
        /// Find all prefabs in the scene and parse the prefabs.
        /// Change the guid's and fileID's on scripts and migrate the fields
        /// </summary>
        /// <param name="sceneFile"></param>
        /// <param name="originalAssetPath"></param>
        /// <param name="destinationAssetPath"></param>
        /// <param name="oldIDs">Needs to be added because the oldIDs can be overriden</param>
        public void MigratePrefabsInAScene(string sceneFile, string originalAssetPath,
                                           string destinationAssetPath,
                                           ref List <ScriptMapping> scriptMappings)
        {
            YamlStream stream = new YamlStream();

            string[] lines = File.ReadAllLines(sceneFile).PrepareSceneForYaml();

            StringReader tempStringReader = new StringReader(string.Join("\r\n", lines));

            stream.Load(tempStringReader);
            tempStringReader.Close();

            List <YamlDocument> yamlPrefabs =
                stream.Documents.Where(document => document.GetName() == "PrefabInstance").ToList();

            List <PrefabModel> prefabs     = prefabController.ExportPrefabs(originalAssetPath);
            List <string>      prefabGuids = yamlPrefabs.Select(document =>
                                                                (string)document.RootNode.GetChildren()["PrefabInstance"]["m_SourcePrefab"]["guid"])
                                             .Distinct()
                                             .ToList();

            foreach (string prefabGuid in prefabGuids)
            {
                PrefabModel currentPrefab = prefabs.FirstOrDefault(model => model.Guid == prefabGuid);
                if (currentPrefab == null)
                {
                    Debug.LogError("Find references to prefab but could not find prefab for guid : " + prefabGuid);
                    continue;
                }

                scriptMappings = MigratePrefab(currentPrefab.Path, originalAssetPath, destinationAssetPath, prefabs,
                                               currentPrefab.Guid, scriptMappings);
            }
        }
        /// <summary>
        /// Write the prefab to a new file
        /// </summary>
        /// <param name="parsedPrefab"></param>
        /// <param name="currentPrefab"></param>
        /// <param name="destination"></param>
        public void SavePrefabFile(string[] parsedPrefab, PrefabModel currentPrefab, string destination)
        {
//            string newPrefabMetaPath = destination + @"\" + Path.GetFileName(currentPrefab.MetaPath);
            string newPrefabMetaPath = destination + currentPrefab.MetaPath.GetRelativeAssetPath();

            if (!Administration.Instance.OverWriteMode)
            {
                newPrefabMetaPath = ProjectPathUtility.AddTimestamp(newPrefabMetaPath);
            }

            if (!Directory.Exists(Path.GetDirectoryName(newPrefabMetaPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(newPrefabMetaPath));
            }

            // For when copying to the same project
            if (currentPrefab.MetaPath != newPrefabMetaPath)
            {
                File.Copy(currentPrefab.MetaPath, newPrefabMetaPath, true);
            }


            string newPrefabPath = newPrefabMetaPath.Substring(0, newPrefabMetaPath.Length - 5);

            if (!Directory.Exists(Path.GetDirectoryName(newPrefabPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(newPrefabPath));
            }


            File.WriteAllText(newPrefabPath,
                              string.Join("\r\n", parsedPrefab));
            Debug.Log("Migrated prefab to : " + newPrefabPath);
        }
Example #3
0
        void FindEnemy()
        {
            var newSelect = PrefabModel.GetPrefab(PrefabModel.currentType, PrefabModel.currentID);

            if (newSelect != select_enemy)
            {
                select_enemy = newSelect;
                OnEnmeyChange(select_enemy);
            }
        }
Example #4
0
        void FindPlayer()
        {
            var newSelect = PrefabModel.GetPrefab(PrefabModel.currentType, PrefabModel.currentID);

            if (newSelect != select_player)
            {
                select_player = newSelect;
                OnPlayerChange(select_player);
            }
        }
        public JsonResult List()
        {
            var mongo = new MongoHelper();

            // 获取所有类别
            var filter = Builders <BsonDocument> .Filter.Eq("Type", "Prefab");

            var categories = mongo.FindMany(Constant.CategoryCollectionName, filter).ToList();

            var particles = mongo.FindAll(Constant.PrefabCollectionName).ToList();

            var list = new List <PrefabModel>();

            foreach (var i in particles)
            {
                var categoryID   = "";
                var categoryName = "";

                if (i.Contains("Category") && !i["Category"].IsBsonNull && !string.IsNullOrEmpty(i["Category"].ToString()))
                {
                    var doc = categories.Where(n => n["_id"].ToString() == i["Category"].ToString()).FirstOrDefault();
                    if (doc != null)
                    {
                        categoryID   = doc["_id"].ToString();
                        categoryName = doc["Name"].ToString();
                    }
                }

                var info = new PrefabModel
                {
                    ID           = i["ID"].AsObjectId.ToString(),
                    Name         = i["Name"].AsString,
                    CategoryID   = categoryID,
                    CategoryName = categoryName,
                    TotalPinYin  = i["TotalPinYin"].ToString(),
                    FirstPinYin  = i["FirstPinYin"].ToString(),
                    CreateTime   = i["CreateTime"].ToUniversalTime(),
                    UpdateTime   = i["UpdateTime"].ToUniversalTime(),
                    Thumbnail    = i.Contains("Thumbnail") && !i["Thumbnail"].IsBsonNull ? i["Thumbnail"].ToString() : null
                };

                list.Add(info);
            }

            list = list.OrderByDescending(n => n.UpdateTime).ToList();

            return(Json(new
            {
                Code = 200,
                Msg = "获取成功!",
                Data = list
            }));
        }
        /// <summary>
        /// Migrate all prefabs
        /// </summary>
        /// <param name="destinationProjectPath"></param>
        /// <param name="originalProjectPath"></param>
        /// <param name="onComplete"></param>
        public void MigrateAllPrefabs(string destinationProjectPath, string originalProjectPath = null,
                                      Action onComplete = null, List <ScriptMapping> scriptMappings = null)
        {
            if (originalProjectPath == null)
            {
                ThreadUtility.RunWaitMainTask(() =>
                {
                    originalProjectPath =
                        EditorUtility.OpenFolderPanel("Export all prefabs in folder", destinationProjectPath, "");
                }
                                              );
            }

            if (string.IsNullOrEmpty(originalProjectPath))
            {
                Debug.Log("Copy prefabs aborted, no path given.");
                return;
            }

            //Deserialize the ScriptMappings
            if (scriptMappings == null && File.Exists(destinationProjectPath + constants.RelativeScriptMappingPath))
            {
                scriptMappings =
                    MappingController.DeserializeMapping(destinationProjectPath + constants.RelativeScriptMappingPath);
            }

            List <PrefabModel> prefabs = prefabController.ExportPrefabs(originalProjectPath + "/Assets");

            for (var i = 0; i < prefabs.Count; i++)
            {
                PrefabModel prefab = prefabs[i];
                MigrationWindow.DisplayProgressBar("Migrating prefab (" + (i + 1) + "/" + prefabs.Count + ")",
                                                   info: "Migrating prefab: " + prefab.Path.Substring(originalProjectPath.Length),
                                                   progress: (float)(i + 1) / prefabs.Count);
                ThreadUtility.RunWaitTask(() =>
                {
                    MigratePrefab(prefab.Path, originalProjectPath, destinationProjectPath, prefabs,
                                  prefab.Guid, scriptMappings);
                }
                                          );
                GC.Collect();
            }

            MigrationWindow.ClearProgressBar();

            ThreadUtility.RunMainTask(() => { AssetDatabase.Refresh(); });
            Debug.Log("Migrated all prefabs");

            if (onComplete != null)
            {
                onComplete.Invoke();
            }
        }
Example #7
0
        void FindConfig(string defend = "Skill")
        {
            if (PrefabModel.currentSkillID == 0)
            {
                var tempSkillList = PrefabModel.GetSkillList(PrefabModel.currentType, PrefabModel.currentID);
                PrefabModel.currentSkillID = int.Parse(tempSkillList[PrefabModel.currentSkillIDIndex]);
            }
            var path = "Assets/Editor/SkillExtension/Config/" + defend + PrefabModel.currentSkillID + ".asset";
            var obj  = AssetDatabase.LoadAssetAtPath <EventNodeScriptableObject>(path);

            if (obj)
            {
                Load(path);
            }
            else
            {
                MessageBox(string.Format($"{defend} config not find id:{PrefabModel.currentSkillID}"));
            }
        }
Example #8
0
        void ExportAllEvents()
        {
            List <string> skillID    = new List <string>();
            var           monsterIDs = PrefabModel.GetMonsterIDs();

            foreach (var k in monsterIDs)
            {
                skillID.AddRange(PrefabModel.GetMonsterSkillList(k));
            }
            var playerIDS = PrefabModel.GetPlayerIDs();

            foreach (var k in playerIDS)
            {
                skillID.AddRange(PrefabModel.GetPlayerSkillList(k));
            }
            foreach (var id in skillID)
            {
                var asset  = AssetDatabase.LoadAssetAtPath <EventNodeScriptableObject>("Assets/Editor/SkillExtension/Config/Skill" + id + ".asset");
                var events = state.GetData(asset);
                SaveAnimationEvents(events, int.Parse(id));
            }
        }
Example #9
0
        void RightTopHelper()
        {
            GUILayout.Space(50);
            bool isSelectChange = false;
            var  typeChange     = (PrefabModel.TableType)EditorGUILayout.EnumPopup(PrefabModel.currentType);

            if (typeChange != PrefabModel.currentType)
            {
                PrefabModel.currentModelIndex   = 0;
                PrefabModel.currentSkillIDIndex = 0;
                PrefabModel.currentType         = typeChange;
                isSelectChange = true;
            }
            var idx     = PrefabModel.GetIDs(PrefabModel.currentType);
            var display = idx.Select(r => r.ToString()).ToArray();


            var modelChange = EditorGUILayout.Popup(PrefabModel.currentModelIndex, display);

            if (modelChange != PrefabModel.currentModelIndex)
            {
                PrefabModel.currentModelIndex   = modelChange;
                PrefabModel.currentSkillIDIndex = 0;
                isSelectChange = true;
            }

            PrefabModel.currentID = idx[PrefabModel.currentModelIndex];
            var displaySkillList = PrefabModel.GetSkillList(PrefabModel.currentType, PrefabModel.currentID);

            var skillChange = EditorGUILayout.Popup(PrefabModel.currentSkillIDIndex, displaySkillList);

            if (skillChange != PrefabModel.currentSkillIDIndex)
            {
                PrefabModel.currentSkillIDIndex = skillChange;
                isSelectChange = true;
            }



            PrefabModel.currentSkillID = int.Parse(displaySkillList[PrefabModel.currentSkillIDIndex]);
            EditorGUILayout.LabelField(PrefabModel.GetSkillName(PrefabModel.currentSkillID));

            if (isSelectChange)
            {
                FindPlayer();
                FindEnemy();
                FindConfig("Skill");
            }

            if (GUILayout.Button("Find Player"))
            {
                FindPlayer();
            }
            if (GUILayout.Button("Find Enemy"))
            {
                FindEnemy();
            }
            if (GUILayout.Button("Find Skill"))
            {
                FindConfig("Skill");
            }
            //if (GUILayout.Button("Find Defend"))
            //{
            //    FindConfig("Defend");
            //}
            if (GUILayout.Button("New"))
            {
                New();
            }
        }
        /// <summary>
        /// Parse the prefab.
        /// Change the guid's and fileID's on scripts and port the fields
        /// </summary>
        /// <param name="prefabFile"></param>
        /// <param name="originalAssetPath"></param>
        /// <param name="destinationAssetPath"></param>
        /// <param name="prefabs"></param>
        /// <param name="prefabGuid"></param>
        /// <exception cref="FormatException"></exception>
        /// <exception cref="NullReferenceException"></exception>
        public List <ScriptMapping> MigratePrefab(string prefabFile, string originalAssetPath, string destinationAssetPath,
                                                  List <PrefabModel> prefabs,
                                                  string prefabGuid, List <ScriptMapping> scriptMappings)
        {
            try
            {
                if (!prefabFile.EndsWith(".prefab"))
                {
                    throw new FormatException("Could not parse prefab, not of type prefab, file : " + prefabFile);
                }

                Debug.Log("Started migration of prefab: " + prefabFile);
                if (BinaryUtility.IsBinaryFile(prefabFile))
                {
                    Debug.LogError("Could not parse file, since it's a binary file. Prefab file: " + prefabFile);
                    return(scriptMappings);
                }

                PrefabModel currentPrefab = prefabs.FirstOrDefault(prefab => prefab.Guid == prefabGuid);
                if (currentPrefab == null)
                {
                    Debug.LogError(
                        "Could not find reference to the prefab with the guid. Might be a model file. Prefab: " +
                        prefabFile);
                    return(scriptMappings);
                }

                string originalProjectPath = ProjectPathUtility.getProjectPathFromFile(prefabFile);

                //Deserialize the old ID's
                List <ClassModel> oldIDs =
                    Administration.Instance.oldIDsOverride ??
                    IDController.DeserializeIDs(originalProjectPath + constants.RelativeExportPath);
                if (oldIDs == null)
                {
                    throw new NullReferenceException("Old IDs not set");
                }

                //Deserialize the new ID's
                List <ClassModel> newIDs =
                    Administration.Instance.newIDsOverride ??
                    IDController.DeserializeIDs(destinationAssetPath + constants.RelativeExportPath);
                if (newIDs == null)
                {
                    throw new NullReferenceException("New IDs not set");
                }

                string[] parsedPrefab = idController.TransformIDs(currentPrefab.Path, oldIDs, newIDs, ref scriptMappings);

                var unmappedScriptMappings = scriptMappings
                                             .Where(script => script.HasBeenMapped == ScriptMapping.MappedState.NotMapped).ToList();
                if (unmappedScriptMappings.Count == 0)
                {
                    parsedPrefab = fieldMappingController.MigrateFields(prefabFile, ref parsedPrefab,
                                                                        ref scriptMappings,
                                                                        originalAssetPath, destinationAssetPath);
                    SavePrefabFile(parsedPrefab, currentPrefab, destinationAssetPath);
                }
                else
                {
                    bool completed = false;
                    ThreadUtility.RunMainTask(() =>
                    {
                        MergeWizard wizard = MergeWizard.CreateWizard(unmappedScriptMappings);
                        wizard.onComplete  = mergedScriptMappings =>
                        {
                            scriptMappings = scriptMappings.Merge(mergedScriptMappings);
                            File.WriteAllText(destinationAssetPath + constants.RelativeScriptMappingPath,
                                              JsonConvert.SerializeObject(scriptMappings, constants.IndentJson));

                            ThreadUtility.RunTask(() =>
                            {
                                parsedPrefab = fieldMappingController.MigrateFields(prefabFile, ref parsedPrefab,
                                                                                    ref scriptMappings, originalAssetPath, destinationAssetPath);
                                SavePrefabFile(parsedPrefab, currentPrefab, destinationAssetPath);
                            });
                            completed = true;
                        };
                    });

                    while (!completed)
                    {
                        Thread.Sleep(constants.THREAD_WAIT_TIME);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.LogError("Could not parse prefab: " + prefabFile + "\r\nException: " + e);
            }

            return(scriptMappings);
        }
Example #11
0
        private void ConvertPrefabsDataInScene(ref string[] scene, string oldRootPath, YamlStream yamlStream,
                                               List <ScriptMapping> scriptMappings)
        {
            // Copy prefabs
            List <YamlDocument> yamlPrefabs =
                yamlStream.Documents.Where(document => document.GetName() == "PrefabInstance").ToList();

            List <PrefabModel> oldPrefabs = prefabController.ExportPrefabs(oldRootPath);

            foreach (YamlDocument prefabInstance in yamlPrefabs)
            {
                //Get the prefab file we're working with
                string      prefabGuid  = (string)prefabInstance.RootNode["PrefabInstance"]["m_SourcePrefab"]["guid"];
                PrefabModel prefabModel = oldPrefabs.FirstOrDefault(prefabFile => prefabFile.Guid == prefabGuid);
                if (prefabModel == null || string.IsNullOrEmpty(prefabModel.Path))
                {
                    Debug.LogWarning(
                        "Found reference to prefab, but could not find the prefab. Might be a model file, not migrating. Prefab guid: " +
                        prefabGuid);
                    continue;
                }

                //Load in the prefab file
                YamlStream   prefabStream     = new YamlStream();
                string[]     lines            = File.ReadAllLines(prefabModel.Path).PrepareSceneForYaml();
                StringReader tempStringReader = new StringReader(string.Join("\r\n", lines));
                prefabStream.Load(tempStringReader);
                tempStringReader.Close();


                //Get the modifications that have been done
                YamlSequenceNode modifications =
                    (YamlSequenceNode)prefabInstance.RootNode["PrefabInstance"]["m_Modification"]["m_Modifications"];

                //change the modifications
                foreach (YamlNode modification in modifications)
                {
                    YamlNode target       = modification["target"];
                    string   fileID       = (string)target["fileID"];
                    string   propertyPath = (string)modification["propertyPath"];

                    YamlDocument scriptReference =
                        prefabStream.Documents.FirstOrDefault(document =>
                                                              document.RootNode.Anchor == fileID);
                    if (scriptReference == null)
                    {
//                        // handle nested prefab
//
//                        int FileID_of_nested_PrefabInstance = 0;
//                        int FileID_of_object_in_nested_Prefab = 0;
//                        var a = (FileID_of_nested_PrefabInstance ^ FileID_of_object_in_nested_Prefab) & 0x7fffffffffffffff;


                        Debug.LogError(
                            "Nested prefab detected! Can not migrate fields in the scene. If there are any field name changes these will not be migrated. Could not find reference to script in file! Currently nested prefabs are not supported.  fileID : " +
                            fileID);
                        continue;
                    }

                    if (scriptReference.GetName() != "MonoBehaviour")
                    {
                        continue;
                    }

                    YamlNode IDs = scriptReference.RootNode["MonoBehaviour"]["m_Script"];

                    string scriptGuid   = (string)IDs["guid"];
                    string scriptFileID = (string)IDs["fileID"];

                    ScriptMapping scriptMappingType =
                        scriptMappings.FirstOrDefault(node =>
                                                      node.oldClassModel.Guid == scriptGuid && node.oldClassModel.FileID == scriptFileID);
                    if (scriptMappingType == null)
                    {
//                        Debug.Log("Could not find mapping for guid: " + scriptGuid + " fileID: " + scriptFileID);
                        continue;
                    }

                    string[]         properties        = propertyPath.Split('.');
                    List <MergeNode> currentMergeNodes = scriptMappingType.MergeNodes;

                    for (var i = 0; i < properties.Length; i++)
                    {
                        string property = properties[i];
                        if (property == "Array" && properties.Length > i + 1 && properties[i + 1].StartsWith("data["))
                        {
                            // this is a list or array and can be skipped;
                            i++;
                            continue;
                        }


                        MergeNode currentMergeNode =
                            currentMergeNodes.FirstOrDefault(node => node.OriginalValue == property);
                        if (currentMergeNode == null)
                        {
                            Debug.Log("Could not find mergeNode for property: " + property);
                            continue;
                        }

                        properties[i] = currentMergeNode.NameToExportTo;

                        currentMergeNodes =
                            scriptMappings
                            .FirstOrDefault(script => script.oldClassModel.FullName == currentMergeNode.Type)
                            ?.MergeNodes;
                    }

                    int line = modification["propertyPath"].Start.Line - 1;
                    scene[line] = scene[line].ReplaceFirst(propertyPath, string.Join(".", properties));
                }
            }
        }
        public JsonResult List()
        {
            var mongo = new MongoHelper();

            // 获取所有类别
            var filter = Builders <BsonDocument> .Filter.Eq("Type", "Prefab");

            var categories = mongo.FindMany(Constant.CategoryCollectionName, filter).ToList();

            var docs = new List <BsonDocument>();

            if (ConfigHelper.EnableAuthority)
            {
                var user = UserHelper.GetCurrentUser();

                if (user != null)
                {
                    var filter1 = Builders <BsonDocument> .Filter.Eq("UserID", user.ID);

                    if (user.Name == "Administrator")
                    {
                        var filter2 = Builders <BsonDocument> .Filter.Exists("UserID");

                        var filter3 = Builders <BsonDocument> .Filter.Not(filter2);

                        filter1 = Builders <BsonDocument> .Filter.Or(filter1, filter3);
                    }
                    docs = mongo.FindMany(Constant.PrefabCollectionName, filter1).ToList();
                }
            }
            else
            {
                docs = mongo.FindAll(Constant.PrefabCollectionName).ToList();
            }

            var list = new List <PrefabModel>();

            foreach (var i in docs)
            {
                var categoryID   = "";
                var categoryName = "";

                if (i.Contains("Category") && !i["Category"].IsBsonNull && !string.IsNullOrEmpty(i["Category"].ToString()))
                {
                    var doc = categories.Where(n => n["_id"].ToString() == i["Category"].ToString()).FirstOrDefault();
                    if (doc != null)
                    {
                        categoryID   = doc["_id"].ToString();
                        categoryName = doc["Name"].ToString();
                    }
                }

                var info = new PrefabModel
                {
                    ID           = i["ID"].AsObjectId.ToString(),
                    Name         = i["Name"].AsString,
                    CategoryID   = categoryID,
                    CategoryName = categoryName,
                    TotalPinYin  = i["TotalPinYin"].ToString(),
                    FirstPinYin  = i["FirstPinYin"].ToString(),
                    CreateTime   = i["CreateTime"].ToUniversalTime(),
                    UpdateTime   = i["UpdateTime"].ToUniversalTime(),
                    Thumbnail    = i.Contains("Thumbnail") && !i["Thumbnail"].IsBsonNull ? i["Thumbnail"].ToString() : null
                };

                list.Add(info);
            }

            list = list.OrderByDescending(n => n.UpdateTime).ToList();

            return(Json(new
            {
                Code = 200,
                Msg = "Get Successfully!",
                Data = list
            }));
        }