Example #1
0
        public void Setup(Type _assetType, string settingPath)
        {
            result = new Result();

            assetType = _assetType;
            dstFolder = CCLogic.GetFilePathRelativesToAssets(settingPath, setting.destination);

            // Asset の名前をつけるときに利用する key.
            keyIndexes = ClassGenerator.FindKeyIndexes(setting, fields);
        }
Example #2
0
        public static IEnumerator ExecuteImport(ConvertSetting s)
        {
            downloadSuccess = false;
            yield return(EditorCoroutineRunner.StartCoroutine(ExecuteDownload(s)));

            if (!downloadSuccess)
            {
                yield break;
            }

            CreateAssetsJob createAssetsJob = new CreateAssetsJob(s);

            // Generate Code if type script is not found.
            Type assetType;

            if (s.isEnum || !CsvConvert.TryGetTypeWithError(s.className, out assetType,
                                                            s.checkFullyQualifiedName, dialog: false))
            {
                GlobalCCSettings gSettings = CCLogic.GetGlobalSettings();
                GenerateOneCode(s, gSettings);

                if (!s.isEnum)
                {
                    EditorUtility.DisplayDialog(
                        "Code Generated",
                        "Please reimport for creating assets after compiling",
                        "ok"
                        );
                }
            }
            // Create Assets
            else
            {
                createAssetsJob.Execute();
            }

            // AfterImport 処理
            for (int i = 0; i < s.executeAfterImport.Count; i++)
            {
                var afterSettings = s.executeAfterImport[i];

                if (afterSettings != null)
                {
                    yield return(EditorCoroutineRunner.StartCoroutine(ExecuteImport(afterSettings)));
                }
            }
        }
Example #3
0
        public static IEnumerator ExecuteDownload(ConvertSetting s)
        {
            GSPluginSettings.Sheet sheet = new GSPluginSettings.Sheet();
            sheet.sheetId = s.sheetID;
            sheet.gid     = s.gid;

            GlobalCCSettings gSettings = CCLogic.GetGlobalSettings();

            string csvPath = s.GetCsvPath(gSettings);

            if (string.IsNullOrWhiteSpace(csvPath))
            {
                Debug.LogError("unexpected downloadPath: " + csvPath);
                downloadSuccess = false;
                yield break;
            }

            string absolutePath = CCLogic.GetFilePathRelativesToAssets(s.GetDirectoryPath(), csvPath);

            // 先頭の Assets を削除する
            if (absolutePath.StartsWith("Assets" + Path.DirectorySeparatorChar))
            {
                sheet.targetPath = absolutePath.Substring(6);
            }
            else
            {
                Debug.LogError("unexpected downloadPath: " + absolutePath);
                downloadSuccess = false;
                yield break;
            }

            sheet.isCsv   = true;
            sheet.verbose = false;

            string title = "Google Spreadsheet Loader";

            yield return(EditorCoroutineRunner.StartCoroutineWithUI(GSEditorWindow.Download(sheet, s.GetDirectoryPath()), title, true));

            // 成功判定を行う.
            if (GSEditorWindow.previousDownloadSuccess)
            {
                downloadSuccess = true;
            }

            yield break;
        }
Example #4
0
        public void Execute()
        {
            GlobalCCSettings gSettings = CCLogic.GetGlobalSettings();

            try
            {
                CsvConvert.CreateAssets(settings, gSettings);
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            EditorUtility.ClearProgressBar();
        }
Example #5
0
        /// <summary>
        /// メインの出力アセットへのパスを指す.
        /// </summary>
        public static string GetMainOutputPath(ConvertSetting s)
        {
            string settingsPath = s.GetDirectoryPath();
            string dst          = "";

            if (s.isEnum)
            {
                dst = CCLogic.GetFilePathRelativesToAssets(settingsPath, s.codeDestination);
                return(Path.Combine(dst, s.className + ".cs"));
            }

            if (s.tableGenerate)
            {
                dst = CCLogic.GetFilePathRelativesToAssets(settingsPath, s.destination);
                return(Path.Combine(dst, s.tableAssetName + ".asset"));
            }

            return(dst);
        }
Example #6
0
        public static void CreateAssets(ConvertSetting s, GlobalCCSettings gSettings)
        {
            string    settingPath = s.GetDirectoryPath();
            string    csvPath     = CCLogic.GetFilePathRelativesToAssets(settingPath, s.GetCsvPath(gSettings));
            TextAsset textAsset   = AssetDatabase.LoadAssetAtPath <TextAsset>(csvPath);

            if (textAsset == null)
            {
                Debug.LogError("Not found : " + csvPath);
                return;
            }

            if (s.isEnum)
            {
                return;
            }

            // csv ファイルから読み込み
            CsvData csv      = CsvLogic.GetValidCsvData(textAsset.text, gSettings);
            CsvData contents = csv.Slice(gSettings.rowIndexOfContentStart);

            Field[] fields = CsvLogic.GetFieldsFromHeader(csv, gSettings);

            // アセットを生成する.
            AssetsGenerator assetsGenerator = new AssetsGenerator(s, fields, contents);

            // カスタムアセットタイプを設定する
            // これはプロジェクト固有のアセットをテーブルでセット出来るようにする.
            {
                Type[] customAssetTypes = new Type[gSettings.customAssetTypes.Length];
                for (int i = 0; i < customAssetTypes.Length; i++)
                {
                    if (TryGetTypeWithError(gSettings.customAssetTypes[i], out var type, s.checkFullyQualifiedName))
                    {
                        customAssetTypes[i] = type;
                    }
Example #7
0
        public static IEnumerator Download(GSPluginSettings.Sheet ss, string settingDir)
        {
            previousDownloadSuccess = false;
            string sheetId = ss.sheetId;
            string gid     = ss.gid;

            string label = "Downloading " + ss.targetPath;

            EditorCoroutineRunner.UpdateUILabel(label);

            var gsLoader       = new GSLoader();
            var globalSettings = CCLogic.GetGlobalSettings();

            string apiKey = globalSettings.apiKey;
            bool   useV4  = globalSettings.useV4;

            yield return(EditorCoroutineRunner.StartCoroutine(gsLoader.LoadGS(sheetId, gid, apiKey, useV4)));

            if (!gsLoader.isSuccess)
            {
                Debug.Log("Failed to load spreadsheet data.");
                yield break;
            }

            CsvData csvData = gsLoader.loadedCsvData;
            string  targetPathRelativeToAssets = ss.GetFilePathRelativesToAssets(settingDir);

            if (csvData != null)
            {
                if (ss.isCsv)
                {
                    string targetDir = Path.GetDirectoryName(targetPathRelativeToAssets);

                    if (!Directory.Exists(targetDir))
                    {
                        try
                        {
                            Directory.CreateDirectory(targetDir);
                            Debug.Log("指定のフォルダが存在しないため、作成しました: " + targetDir);
                        }
                        catch (Exception e)
                        {
                            Debug.LogError("指定のフォルダの作成に失敗: " + e.Message);
                        }
//                            Debug.LogError("指定のフォルダは存在しません: " + targetDir);
//                        return;
                    }

                    using (var s = new StreamWriter(targetPathRelativeToAssets)) {
                        s.Write(csvData.ToString());
                    }
                }
                else
                {
                    // AssetDatabase.CreateAsset(csvData, targetPathRelativeToAssets);
                    Debug.LogError("CsvData の書き出しには未対応になりました");
                }

                if (ss.verbose)
                {
                    Debug.Log("Write " + ss.targetPath);
                }

                previousDownloadSuccess = true;
                AssetDatabase.Refresh();
            }
            else
            {
                Debug.LogError("Fails for " + ss.ToString());
            }
        }
Example #8
0
        private void OnGUI()
        {
            GUILayout.Space(6f);
            ConvertSetting[] settings = null;

            if (cachedAllSettings != null)
            {
                settings = cachedAllSettings;
            }

            // 検索ボックスを表示
            GUILayout.BeginHorizontal();
            searchTxt = SearchField(searchTxt);
            searchTxt = searchTxt.ToLower();
            GUILayout.EndHorizontal();

            if (settings != null)
            {
                scrollPosition = GUILayout.BeginScrollView(scrollPosition);

                for (int i = 0; i < settings.Length; i++)
                {
                    var s = settings[i];

                    // 設定が削除されている場合などに対応
                    if (s == null)
                    {
                        continue;
                    }

                    // 検索ワードチェック
                    if (!string.IsNullOrEmpty(searchTxt))
                    {
                        if (s.tableGenerate)
                        {
                            if (!searchTxt.IsSubsequence(s.tableAssetName.ToLower()))
                            {
                                continue;
                            }
                        }
                        else
                        {
                            if (!searchTxt.IsSubsequence(s.className.ToLower()))
                            {
                                continue;
                            }
                        }
                    }

                    GUILayout.BeginHorizontal("box");

#if ODIN_INSPECTOR
                    // ------------------------------
                    // 設定を複製ボタン.
                    // ------------------------------
                    if (GUILayout.Button("+", GUILayout.Width(20)))
                    {
                        var copied = s.Copy();

                        var window = CCSettingsEditWindow.OpenWindow();
                        window.SetNewSettings(copied, s.GetDirectoryPath());

                        GUIUtility.ExitGUI();
                    }

                    // ------------------------------
                    // 設定を編集ボタン.
                    // ------------------------------
                    var edit = EditorGUIUtility.Load("editicon.sml") as Texture2D;
                    if (GUILayout.Button(edit, GUILayout.Width(20)))
                    {
                        var window = CCSettingsEditWindow.OpenWindow();
                        window.SetSettings(s);
                        GUIUtility.ExitGUI();
                    }
#endif

                    // ------------------------------
                    // テーブル名 (enum の場合は enum名) を表示.
                    // クリックして、設定ファイルに飛べるようにする.
                    // ------------------------------
                    if (s.tableGenerate)
                    {
                        if (GUILayout.Button(s.tableAssetName, "Label"))
                        {
                            EditorGUIUtility.PingObject(s.GetInstanceID());
                            GUIUtility.ExitGUI();
                        }
                    }
                    else
                    {
                        if (GUILayout.Button(s.className, "Label"))
                        {
                            EditorGUIUtility.PingObject(s.GetInstanceID());
                            GUIUtility.ExitGUI();
                        }
                    }

                    // ------------------------------
                    // GS Plugin 使う場合のボタン.
                    //
                    // Import ボタン
                    // Open ボタン
                    // ------------------------------
                    if (s.useGSPlugin)
                    {
                        if (GUILayout.Button("Import", GUILayout.Width(110)))
                        {
                            EditorCoroutineRunner.StartCoroutine(ExecuteImport(s));
                            GUIUtility.ExitGUI();
                        }

                        // GS Plugin を使う場合は Open ボタンを用意する.
                        if (s.useGSPlugin)
                        {
                            if (GUILayout.Button("Open", GUILayout.Width(80)) && !isDownloading)
                            {
                                GSUtils.OpenURL(s.sheetID, s.gid);
                                GUIUtility.ExitGUI();
                            }
                        }


                        if (s.verboseBtn)
                        {
                            if (GUILayout.Button("DownLoad", GUILayout.Width(110)))
                            {
                                EditorCoroutineRunner.StartCoroutine(ExecuteDownload(s));
                                GUIUtility.ExitGUI();
                            }
                        }
                    }

                    // ------------------------------
                    // コード生成ボタン.
                    // v0.1.2 からは Import に置き換え.
                    // ------------------------------
                    if (s.verboseBtn)
                    {
                        GUI.enabled = s.canGenerateCode;
                        if (GUILayout.Button("Generate Code", GUILayout.Width(110)) && !isDownloading)
                        {
                            GlobalCCSettings gSettings = CCLogic.GetGlobalSettings();
                            isDownloading = true;
                            GenerateOneCode(s, gSettings);
                            isDownloading = false;

                            GUIUtility.ExitGUI();
                        }
                    }

                    // ------------------------------
                    // アセット生成ボタン.
                    // v0.1.2 からは Import に置き換え.
                    // ------------------------------
                    if (s.verboseBtn)
                    {
                        GUI.enabled = s.canCreateAsset;

                        if (GUILayout.Button("Create Assets", GUILayout.Width(110)) && !isDownloading)
                        {
                            CreateAssetsJob createAssetsJob = new CreateAssetsJob(s);
                            createAssetsJob.Execute();
                            GUIUtility.ExitGUI();
                        }
                    }

                    GUI.enabled = true;

                    // ------------------------------
                    // 成果物参照まど.
                    // ------------------------------
                    {
                        Object outputRef = null;

                        if (s.join)
                        {
                            outputRef = s.targetTable;
                        }
                        else
                        {
                            string mainOutputPath = CCLogic.GetMainOutputPath(s);

                            if (mainOutputPath != null)
                            {
                                outputRef = AssetDatabase.LoadAssetAtPath <Object>(mainOutputPath);
                            }
                        }

                        EditorGUI.BeginDisabledGroup(true);
                        EditorGUILayout.ObjectField(outputRef, typeof(Object), false, GUILayout.Width(100));
                        EditorGUI.EndDisabledGroup();
                    }

                    GUILayout.EndHorizontal();
                }

                GUILayout.EndScrollView();

                GUILayout.BeginHorizontal("box");
                if (GUILayout.Button("Generate All Codes", "LargeButtonMid") && !isDownloading)
                {
                    GlobalCCSettings gSettings = CCLogic.GetGlobalSettings();
                    isDownloading = true;
                    GenerateAllCode(settings, gSettings);
                    isDownloading = false;

                    GUIUtility.ExitGUI();
                }

                if (GUILayout.Button("Create All Assets", "LargeButtonMid") && !isDownloading)
                {
                    GlobalCCSettings gSettings = CCLogic.GetGlobalSettings();
                    isDownloading = true;
                    CreateAllAssets(settings, gSettings);
                    isDownloading = false;

                    GUIUtility.ExitGUI();
                }

                GUILayout.EndHorizontal();
            }
        }
Example #9
0
        public static void GenerateCode(ConvertSetting s, GlobalCCSettings gSettings)
        {
            string    settingPath = s.GetDirectoryPath();
            string    csvPath     = CCLogic.GetFilePathRelativesToAssets(settingPath, s.GetCsvPath(gSettings));
            TextAsset textAsset   = AssetDatabase.LoadAssetAtPath <TextAsset>(csvPath);

            if (textAsset == null)
            {
                Debug.LogError("Not found : " + csvPath);
                return;
            }

            string directoryPath = CCLogic.GetFullPath(settingPath, s.codeDestination);

            if (!Directory.Exists(directoryPath))
            {
                Debug.LogError("Not found directory: " + directoryPath);
                return;
            }

            CsvData csv = CsvLogic.GetValidCsvData(textAsset.text, gSettings);

            if (s.isEnum)
            {
                CsvData headers  = csv.Slice(gSettings.rowIndexOfName, gSettings.rowIndexOfName + 1);
                CsvData contents = csv.Slice(gSettings.rowIndexOfEnumContentStart);
                string  code     = EnumGenerator.Generate(s.className, headers, contents, s.verbose);

                string filePath = Path.Combine(directoryPath, s.className + ".cs");
                using (StreamWriter writer = File.CreateText(filePath))
                {
                    writer.WriteLine(code);
                }

                Debug.LogFormat("Create \"{0}\"", filePath);
            }
            else
            {
                Field[] fields = CsvLogic.GetFieldsFromHeader(csv, gSettings);

                if (s.classGenerate)
                {
                    string code = ClassGenerator.GenerateClass(s.className, fields, s.IsPureClass);

                    string filePath = Path.Combine(directoryPath, s.className + ".cs");
                    using (StreamWriter writer = File.CreateText(filePath))
                    {
                        writer.WriteLine(code);
                    }

                    Debug.LogFormat("Create \"{0}\"", filePath);
                }

                if (s.tableClassGenerate)
                {
                    int[] keyIndexes = ClassGenerator.FindKeyIndexes(s, fields);

                    string[] keys = s.keys;
                    Field[]  key  = null;
                    if (keyIndexes.Length > 0)
                    {
                        List <Field> keyFieldList = new List <Field>();

                        for (int i = 0; i < keyIndexes.Length; i++)
                        {
                            keyFieldList.Add(fields[keyIndexes[i]]);
                        }

                        key = keyFieldList.ToArray();
                    }

                    string code = ClassGenerator.GenerateTableClass(s, s.TableClassName, key);

                    string filePath = Path.Combine(directoryPath, s.TableClassName + ".cs");
                    using (StreamWriter writer = File.CreateText(filePath))
                    {
                        writer.WriteLine(code);
                    }

                    Debug.LogFormat("Create \"{0}\"", filePath);
                }
            }

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
Example #10
0
        public static object Convert(Type t, string sValue)
        {
            sValue = sValue.Trim();
#if VERBOSE
            Debug.Log("Convert: #" + sValue + "#");
#endif
            object value = null;
            // 型に応じて string を変換する.
            if (t == typeof(int))
            {
                int intValue;
                if (int.TryParse(sValue, out intValue))
                {
                    value = intValue;
                }
                else
                {
                    // enum チェックする
                    // 例えば int フィールドとして `KeyCode.Tab` のような値も許容するようにする.
                    string[] splits = sValue.Split('.');

                    if (splits.Length == 2)
                    {
                        string typeName = splits[0];
                        string enumId   = splits[1];

                        List <Type> candidates = CCLogic.GetTypeByName(typeName);

                        if (candidates.Count > 2)
                        {
                            Debug.LogWarningFormat("指定の enum が複数見つかりました", typeName);
                        }
                        else if (candidates.Count == 1)
                        {
                            value = Enum.Parse(candidates[0], enumId);
                        }
                    }
                }
            }
            else if (t == typeof(float))
            {
                float floatValue;
                if (float.TryParse(sValue, out floatValue))
                {
                    value = floatValue;
                }
            }
            else if (t == typeof(double))
            {
                double doubleValue;
                if (double.TryParse(sValue, out doubleValue))
                {
                    value = doubleValue;
                }
            }
            else if (t == typeof(long))
            {
                long longValue;
                if (long.TryParse(sValue, out longValue))
                {
                    value = longValue;
                }
            }
            else if (t == typeof(bool))
            {
                bool cValue;
                if (bool.TryParse(sValue, out cValue))
                {
                    value = cValue;
                }
            }
            else if (t == typeof(GameObject))
            {
                value = LoadAsset <GameObject>(sValue);
            }
            else if (t == typeof(Sprite))
            {
                value = LoadAsset <Sprite>(sValue);
            }
            else if (t == typeof(AudioClip))
            {
                value = LoadAsset <AudioClip>(sValue);
            }
            else if (t == typeof(Material))
            {
                value = LoadAsset <Material>(sValue);
            }
            else if (t == typeof(string))
            {
                if ((sValue[0] == '"' && sValue[sValue.Length - 1] == '"') ||
                    (sValue[0] == '\'' && sValue[sValue.Length - 1] == '\''))
                {
                    value = sValue.Substring(1, sValue.Length - 2);
                }
            }
            else if (t == typeof(Vector2))
            {
                // 両端の "(" をとる
                sValue = sValue.Substring(1, sValue.Length - 2);
                string[] splits = sValue.Split(',');

                Vector2 vector = Vector2.zero;

                for (int i = 0; i < splits.Length; i++)
                {
                    string elemValue = splits[i].Trim();

                    if (elemValue == "")
                    {
                        return(null);
                    }

                    object elem = Convert(typeof(float), elemValue);

                    if (elem == null)
                    {
                        return(null);
                    }

                    vector[i] = (float)elem;
                }

                value = vector;
            }
            else if (t == typeof(Vector3))
            {
                // 両端の "(" をとる
                sValue = sValue.Substring(1, sValue.Length - 2);
                string[] splits = sValue.Split(',');

                Vector3 vector = Vector3.zero;

                for (int i = 0; i < splits.Length; i++)
                {
                    string elemValue = splits[i].Trim();

                    if (elemValue == "")
                    {
                        return(null);
                    }

                    object elem = Convert(typeof(float), elemValue);

                    if (elem == null)
                    {
                        return(null);
                    }

                    vector[i] = (float)elem;
                }

                value = vector;
            }
            else if (t.IsArray)
            {
                // TODO 文字列中にカンマがあったときに対応できない.
                sValue = sValue.Substring(1, sValue.Length - 2);
                string[] splits = sValue.Split(',');

                // TODO List<object> だと Cast Error が発生する...
                //List<int> objects = new List<int>();

                //Debug.Log("t.GetElementType() = " + t.GetElementType());
                Type listType            = typeof(List <>);
                var  constructedListType = listType.MakeGenericType(t.GetElementType());

                var objects = Activator.CreateInstance(constructedListType);

                for (int i = 0; i < splits.Length; i++)
                {
                    Type   elemType  = t.GetElementType();
                    string elemValue = splits[i].Trim();

                    if (elemValue == "")
                    {
                        continue;
                    }

                    object elem = Convert(elemType, elemValue);

                    if (elem == null)
                    {
                        return(null);
                    }

                    //objects.GetType().
                    //objects.Add((int)elem);
                    objects.GetType().GetMethod("Add").Invoke(objects, new object[] { elem });
                }

                //value = System.Convert.ChangeType(objects.ToArray(), t);
                //value = objects.ToArray();
                value = objects.GetType().GetMethod("ToArray").Invoke(objects, new object[] { });
            }
            // ユーザー定義型の enum
            else if (t.IsEnum)
            {
                Type fieldType = t;
                value = Enum.Parse(fieldType, sValue);
            }
            else
            {
                return(null);
            }

            return(value);
        }