// Write images to specified unity image directory. public void WriteImages() { foreach (var img in data) { string meta = img.Value.ToString().Split(',')[0]; string data = img.Value.ToString().Split(',')[1]; data = data.Trim('"'); // Make sure our base64 string is padded switch (data.Length % 4) { case 2: data += "=="; break; case 3: data += "="; break; default: break; } byte[] imgbytes = Convert.FromBase64String(data); // Write file File.WriteAllBytes(Application.dataPath + "/" + CastleDBConfig.Instance().ImagesFolder + "/" + img.Key + "." + GetFileExtension(meta), imgbytes); data = null; } }
/// <summary> /// Rebuilds defines based on what dbs are currently built. This allows for conditional compilation directives in the sample, so the sample doesn't cause compile errors, but is probably useful elsewhere. /// </summary> public static void RefreshDefines() { // Get all defines string definesString = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup); List <string> allDefines = definesString.Split(';').ToList(); // Delete all defines that are CDBIMPORT tags. allDefines.RemoveAll(u => u.EndsWith("_CDBIMPORT")); // Get all db dirs var path = Application.dataPath + Path.DirectorySeparatorChar + CastleDBConfig.Instance().GeneratedTypesLocation; // If our dir exists, add import defines if (Directory.Exists(path)) { var info = new DirectoryInfo(path); var directories = info.GetDirectories(); // Add each db we currently have imported foreach (var d in directories) { allDefines.Add(d.Name.ToUpper() + "_CDBIMPORT"); } } // Replace our define string PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, string.Join(";", allDefines.ToArray())); }
void SetImporterOptions() { var guids = AssetDatabase.FindAssets("CastleDBConfig t:CastleDBConfig"); var path = AssetDatabase.GUIDToAssetPath(guids[0]); Config = AssetDatabase.LoadAssetAtPath(path, typeof(CastleDBConfig)) as CastleDBConfig; }
public static void InitTypePath(CastleDBConfig config) { var path = $"{Application.dataPath}/{config.GeneratedTypesLocation}"; if (Directory.Exists(path)) { //we've generated this before, so delete the assets in the folder and refresh the DB var files = Directory.GetFiles(path); foreach (var file in files) { FileUtil.DeleteFileOrDirectory(file); } AssetDatabase.Refresh(); } else { Directory.CreateDirectory(path); AssetDatabase.Refresh(); } }
public override void OnImportAsset(AssetImportContext ctx) { // Make sure this .img file is part of a CastleDB database if (!HasCorrespondingCDBFile(ctx.assetPath)) { return; } // Make Images Folder CastleDBGenerator.InitPath(CastleDBConfig.Instance().ImagesFolder); // Import as TextAsset TextAsset images = new TextAsset(File.ReadAllText(ctx.assetPath)); ctx.AddObjectToAsset("main obj", images); ctx.SetMainObject(images); // Decode and import images as assets data = JSON.Parse(images.text); EditorApplication.delayCall += new EditorApplication.CallbackFunction(WriteImages); }
private void GenerateTypes() { CastleDBGenerator.GenerateTypes(parser.Root, CastleDBConfig.Instance(), dbname); parser = null; dbname = ""; }
public static void InitTypePath(CastleDBConfig config) { InitPath(config.GeneratedTypesLocation); }
public static void GenerateTypes(CastleDBParser.RootNode root, CastleDBConfig configFile, string dbname) { // Create scripts List <string> scripts = new List <string>(); CastleDBConfig config = configFile; String FieldIndent = " "; InitTypePath(config); InitPath(configFile.GeneratedTypesLocation + $"/{dbname}/"); foreach (CastleDBParser.SheetNode sheet in root.Sheets) { string scriptPath = $"Assets/{config.GeneratedTypesLocation}/{dbname}/{sheet.Name}.cs"; scripts.Add(scriptPath); //generate fields string fieldText = ""; for (int i = 0; i < sheet.Columns.Count; i++) { fieldText += FieldIndent; CastleDBParser.ColumnNode column = sheet.Columns[i]; string fieldType = CastleDBUtils.GetTypeFromCastleDBColumn(column); if (fieldType != "Enum") //non-enum, normal field { if (CastleDBUtils.GetTypeNumFromCastleDBTypeString(column.TypeStr) == "8") { fieldText += ($"public List<{fieldType}> {column.Name}List = new List<{fieldType}>();"); } else { fieldText += ($"public {fieldType} {column.Name};"); } } else //enum type { string[] enumValueNames = CastleDBUtils.GetEnumValuesFromTypeString(column.TypeStr); string enumEntries = ""; if (CastleDBUtils.GetTypeNumFromCastleDBTypeString(column.TypeStr) == "10") //flag { fieldText += ($"public {column.Name}Flag {column.Name};"); for (int val = 0; val < enumValueNames.Length; val++) { enumEntries += (enumValueNames[val] + " = " + (int)Math.Pow(2, val)); if (val + 1 < enumValueNames.Length) { enumEntries += ","; } ; } fieldText += ($"[FlagsAttribute] public enum {column.Name}Flag {{ {enumEntries} }}"); } else { fieldText += ($"public {column.Name}Enum {column.Name};"); for (int val = 0; val < enumValueNames.Length; val++) { enumEntries += (enumValueNames[val] + " = " + val); if (val + 1 < enumValueNames.Length) { enumEntries += ","; } ; } fieldText += ($"public enum {column.Name}Enum {{ {enumEntries} }}"); } } fieldText += "\r\n"; } #region ("Row Values Field") string possibleValuesText = ""; if (!sheet.NestedType) { possibleValuesText += $"public enum RowValues {{"; for (int i = 0; i < sheet.Rows.Count; i++) { string rowName = sheet.Rows[i][config.GUIDColumnName]; possibleValuesText += rowName; if (i + 1 < sheet.Rows.Count) { possibleValuesText += " , "; } } possibleValuesText += " }\r\n"; } #endregion //generate the constructor that sets the fields based on the passed in value string constructorText = ""; string constructorIndent = " "; if (!sheet.NestedType) { constructorText += $"{constructorIndent}SimpleJSON.JSONNode node = root.GetSheetWithName(\"{sheet.Name}\").Rows[(int)line];\r\n"; } for (int i = 0; i < sheet.Columns.Count; i++) { constructorText += constructorIndent; CastleDBParser.ColumnNode column = sheet.Columns[i]; string castText = CastleDBUtils.GetCastStringFromCastleDBTypeStr(column.TypeStr); string enumCast = ""; string typeNum = CastleDBUtils.GetTypeNumFromCastleDBTypeString(column.TypeStr); if (typeNum == "8") { //list type constructorText += $"foreach(var item in node[\"{column.Name}\"]) {{ {column.Name}List.Add(new {column.Name}(root, item));}}"; } else if (typeNum == "6") { //working area: //ref type string refType = CastleDBUtils.GetTypeFromCastleDBColumn(column); //look up the line based on the passed in row constructorText += $"{column.Name} = new {refType}(root,{refType}.GetRowValue(node[\"{column.Name}\"]));"; } else if (typeNum == "7") // Image { constructorText += $"{column.Name} = Resources.Load<Texture>(node[\"{column.Name}\"]) as Texture;"; } else if (typeNum == "11") // Color { constructorText += $"{column.Name} = CastleDBUtils.GetColorFromString( node[\"{column.Name}\"]);"; } else { if (typeNum == "10") { enumCast = $"({column.Name}Flag)"; } else if (typeNum == "5") { enumCast = $"({column.Name}Enum)"; } constructorText += $"{column.Name} = {enumCast}node[\"{column.Name}\"]{castText};"; } constructorText += "\r\n"; } string getMethodText = ""; if (!sheet.NestedType) { getMethodText += $@" public static {sheet.Name}.RowValues GetRowValue(string name) {{ var values = (RowValues[])Enum.GetValues(typeof(RowValues)); for (int i = 0; i < values.Length; i++) {{ if(values[i].ToString() == name) {{ return values[i]; }} }} return values[0]; }}"; } string ctor = ""; if (!sheet.NestedType) { ctor = $"public {sheet.Name} (CastleDBParser.RootNode root, RowValues line)"; } else { ctor = $"public {sheet.Name} (CastleDBParser.RootNode root, SimpleJSON.JSONNode node)"; } // string usings = "using UnityEngine;\r\n using System;\r\n using System.Collections.Generic;\r\n using SimpleJSON;\r\n using CastleDBImporter;\r\n"; string fullClassText = $@" using UnityEngine; using System; using System.Collections.Generic; using SimpleJSON; using CastleDBImporter; using {config.GeneratedTypesNamespace}.{dbname}; namespace {config.GeneratedTypesNamespace}.{dbname} {{ public class {sheet.Name} {{ {fieldText} {possibleValuesText} {ctor} {{ {constructorText} }} {getMethodText} }} }}"; if (!config.SuppressBuildInfo) { Debug.Log("Generating CDB Class: " + sheet.Name); } File.WriteAllText(scriptPath, fullClassText); } //build the CastleDB file string cdbscriptPath = $"Assets/{config.GeneratedTypesLocation}/{dbname}/{dbname}.cs"; scripts.Add(cdbscriptPath); //fields string cdbfields = ""; string cdbconstructorBody = ""; string classTexts = ""; foreach (CastleDBParser.SheetNode sheet in root.Sheets) { if (sheet.NestedType) { continue; } //only write main types to CastleDB cdbfields += $" public {sheet.Name}Type {sheet.Name};\r\n"; cdbconstructorBody += $" {sheet.Name} = new {sheet.Name}Type();\r\n"; //get a list of all the row names classTexts += $" public class {sheet.Name}Type \r\n {{\r\n"; for (int i = 0; i < sheet.Rows.Count; i++) { string rowName = sheet.Rows[i][config.GUIDColumnName]; classTexts += $" public {sheet.Name} {rowName} {{ get {{ return Get({configFile.GeneratedTypesNamespace}.{dbname}.{sheet.Name}.RowValues.{rowName}); }} }} \r\n"; } classTexts += $" private {sheet.Name} Get({sheet.Name}.RowValues line) {{ return new {sheet.Name}(parsedDB.Root, line); }}\r\n"; classTexts += $@" public {sheet.Name}[] GetAll() {{ var values = ({sheet.Name}.RowValues[])Enum.GetValues(typeof({sheet.Name}.RowValues)); {sheet.Name}[] returnList = new {sheet.Name}[values.Length]; for (int i = 0; i < values.Length; i++) {{ returnList[i] = Get(values[i]); }} return returnList; }}"; classTexts += $"\r\n }} //END OF {sheet.Name} \r\n\r\n"; } string fullCastle = $@" using UnityEngine; using CastleDBImporter; using System.Collections.Generic; using System; using {config.GeneratedTypesNamespace}.{dbname}; namespace {config.GeneratedTypesNamespace}.{dbname} {{ public class {dbname} {{ static CastleDBParser parsedDB; {cdbfields} {classTexts} public {dbname}(TextAsset castleDBAsset) {{ parsedDB = new CastleDBParser(castleDBAsset); {cdbconstructorBody} }} }} }}"; if (!config.SuppressBuildInfo) { Debug.Log("Generating CastleDB class"); if (CastleDBConfig.NamesHaveSpaces) { Debug.Log("Your CastleDB file contains spaces in names! These spaces will be automatically converted to '_'."); } Debug.Log("To suppress log messages from import, check the CastleDBConfig flag 'Suppress Import Messages'"); } File.WriteAllText(cdbscriptPath, fullCastle); AssetDatabase.Refresh(); }
public static void GenerateTypes(CastleDBParser.RootNode root, CastleDBConfig configFile) { // Create scripts List <string> scripts = new List <string>(); CastleDBConfig config = configFile; InitTypePath(config); foreach (CastleDBParser.SheetNode sheet in root.Sheets) { Debug.Log("Doinog: " + sheet.Name); string scriptPath = $"Assets/{config.GeneratedTypesLocation}/{sheet.Name}.cs"; scripts.Add(scriptPath); //generate fields string fieldText = ""; for (int i = 0; i < sheet.Columns.Count; i++) { CastleDBParser.ColumnNode column = sheet.Columns[i]; string fieldType = CastleDBUtils.GetTypeFromCastleDBColumn(column); if (fieldType != "Enum") //non-enum, normal field { if (CastleDBUtils.GetTypeNumFromCastleDBTypeString(column.TypeStr) == "8") { fieldText += ($"public List<{fieldType}> {column.Name}List = new List<{fieldType}>();\n\t\t"); } else { fieldText += ($"public {fieldType} {column.Name};\n\t\t"); } } else //enum type { string[] enumValueNames = CastleDBUtils.GetEnumValuesFromTypeString(column.TypeStr); string enumEntries = ""; if (CastleDBUtils.GetTypeNumFromCastleDBTypeString(column.TypeStr) == "10") //flag { fieldText += ($"public {column.Name}Flag {column.Name};\n"); for (int val = 0; val < enumValueNames.Length; val++) { enumEntries += (enumValueNames[val] + " = " + (int)Math.Pow(2, val)); if (val + 1 < enumValueNames.Length) { enumEntries += ","; } ; } fieldText += ($"[FlagsAttribute] public enum {column.Name}Flag {{ {enumEntries} }}"); } else { fieldText += ($"public {column.Name}Enum {column.Name};\n"); for (int val = 0; val < enumValueNames.Length; val++) { enumEntries += (enumValueNames[val] + " = " + val); if (val + 1 < enumValueNames.Length) { enumEntries += ","; } ; } fieldText += ($"public enum {column.Name}Enum {{ {enumEntries} }}"); } } } //generate the constructor that sets the fields based on the passed in value StringBuilder constructorText = new StringBuilder(); for (int i = 0; i < sheet.Columns.Count; i++) { CastleDBParser.ColumnNode column = sheet.Columns[i]; string castText = CastleDBUtils.GetCastStringFromCastleDBTypeStr(column.TypeStr); string enumCast = ""; string typeNum = CastleDBUtils.GetTypeNumFromCastleDBTypeString(column.TypeStr); if (typeNum == "8") { //list type if (CastleDBUtils.DoesSheetContainImages(root, root.GetSheetWithName(column.Name))) { constructorText.Append($"\t\t\tforeach(var item in node[\"{column.Name}\"]) {{ {column.Name}List.Add(new {column.Name}(root, item, DatabaseImages));}}\n"); } else { constructorText.Append($"\t\t\tforeach(var item in node[\"{column.Name}\"]) {{ {column.Name}List.Add(new {column.Name}(root, item));}}\n"); } } else if (typeNum == "6") { //working area: //ref type string refType = CastleDBUtils.GetTypeFromCastleDBColumn(column); //look up the line based on the passed in row if (CastleDBUtils.DoesSheetContainImages(root, sheet)) { constructorText.Append( $"{column.Name} = new {config.GeneratedTypesNamespace}.{refType}(root, root.GetSheetWithName(\"{refType}\")." + $"Rows.Find( pred => pred[\"{config.GUIDColumnName}\"] == node[\"{column.Name}\"]), DatabaseImages);\n" ); } else { constructorText.Append( $"{column.Name} = new {config.GeneratedTypesNamespace}.{refType}(root, root.GetSheetWithName(\"{refType}\")." + $"Rows.Find( pred => pred[\"{config.GUIDColumnName}\"] == node[\"{column.Name}\"]));\n" ); } } else if (typeNum == "7") // Image type { constructorText.Append($"\t\t\t{column.Name} = DatabaseImages[node[\"{column.Name}\"]];\n"); } else { if (typeNum == "10") { enumCast = $"({column.Name}Flag)"; } else if (typeNum == "5") { enumCast = $"({column.Name}Enum)"; } constructorText.Append($"\t\t\t{column.Name} = {enumCast}node[\"{column.Name}\"]{castText};\n"); } } string ctor = ""; if (CastleDBUtils.DoesSheetContainImages(root, sheet)) { ctor = $"public {sheet.Name} (CastleDBParser.RootNode root, SimpleJSON.JSONNode node, Dictionary<string, Texture> DatabaseImages)"; } else { ctor = $"public {sheet.Name} (CastleDBParser.RootNode root, SimpleJSON.JSONNode node)"; } string fullClassText = $@" using UnityEngine; using System; using System.Collections.Generic; using SimpleJSON; using CastleDBImporter; namespace {config.GeneratedTypesNamespace} {{ public class {sheet.Name} {{ {fieldText} {ctor} {{ {constructorText} }} }} }}"; Debug.Log("Generating CDB Class: " + sheet.Name); File.WriteAllText(scriptPath, fullClassText); } //build the CastleDB file string cdbscriptPath = $"Assets/{config.GeneratedTypesLocation}/CastleDB.cs"; scripts.Add(cdbscriptPath); //fields string cdbfields = ""; string cdbconstructorBody = ""; foreach (CastleDBParser.SheetNode sheet in root.Sheets) { if (sheet.NestedType) { continue; } //only write main types to CastleDB cdbfields += $"public Dictionary<string, {sheet.Name}> {sheet.Name};\n"; cdbconstructorBody += $"{sheet.Name} = new Dictionary<string, {sheet.Name}>();\n"; //get a list of all the row names cdbconstructorBody += $"\t\t\tforeach( var row in root.GetSheetWithName(\"{sheet.Name}\").Rows ) {{\n"; if (CastleDBUtils.DoesSheetContainImages(root, sheet)) { cdbconstructorBody += $"\t\t\t\t{sheet.Name}[row[\"id\"]] = new {sheet.Name}(root, row, parsedDB.DatabaseImages);\n\t\t\t}}"; } else { cdbconstructorBody += $"\t\t\t\t{sheet.Name}[row[\"id\"]] = new {sheet.Name}(root, row);\n\t\t\t}}"; } } string fullCastle = $@" using UnityEngine; using CastleDBImporter; using System.Collections.Generic; using System; namespace {config.GeneratedTypesNamespace} {{ public class CastleDB {{ static CastleDBParser parsedDB; {cdbfields} public CastleDB(TextAsset castleDBAsset, TextAsset castleDBImagesAsset = null) {{ parsedDB = new CastleDBParser(castleDBAsset, castleDBImagesAsset); CastleDBParser.RootNode root = parsedDB.Root; { cdbconstructorBody } }} }} }}"; Debug.Log("Generating CastleDB class"); File.WriteAllText(cdbscriptPath, fullCastle); AssetDatabase.Refresh(); }