Exemplo n.º 1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="force">Whether or not,check diff.  false will be faster!</param>
        /// <param name="genCode">Generate static code?</param>
        public static void DoCompileSettings(bool force = true, string forceTemplate = null)
        {
            var sourcePath = SettingSourcePath;//AppEngine.GetConfig("SettingSourcePath");

            if (string.IsNullOrEmpty(sourcePath))
            {
                Log.Error("Need to KEngineConfig: SettingSourcePath");
                return;
            }
            var compilePath = AppEngine.GetConfig("KEngine.Setting", "SettingCompiledPath");

            if (string.IsNullOrEmpty(compilePath))
            {
                Log.Error("Need to KEngineConfig: SettingCompiledPath");
                return;
            }

            var bc = new BatchCompiler();

            var settingCodeIgnorePattern = AppEngine.GetConfig("KEngine.Setting", "SettingCodeIgnorePattern", false);
            var results = bc.CompileTableMLAll(sourcePath, compilePath, SettingCodePath, forceTemplate ?? DefaultTemplate.GenCodeTemplate, "AppSettings", SettingExtension, settingCodeIgnorePattern, force);

            //            CompileTabConfigs(sourcePath, compilePath, SettingCodePath, SettingExtension, force);
            var sb = new StringBuilder();

            foreach (var r in results)
            {
                sb.AppendLine(string.Format("Excel {0} -> {1}", r.ExcelFile, r.TabFileRelativePath));
            }
            Log.Info("TableML all Compile ok!\n{0}", sb.ToString());
            // make unity compile
            AssetDatabase.Refresh();
        }
Exemplo n.º 2
0
    //
    /// <summary>
    /// 如果非realBuild,僅返回最終路徑
    /// DoBuildAssetBundle和__DoBuildScriptableObject有两个开关,决定是否真的Build
    /// realBuildOrJustPath由外部传入,一般用于进行md5比较后,传入来的,【不收集Build缓存】 TODO:其实可以收集的。。
    /// IsJustCollect用于全局的否决真Build,【收集Build缓存】
    /// </summary>
    /// <param name="path"></param>
    /// <param name="asset"></param>
    /// <param name="realBuildOrJustPath"></param>
    /// <returns></returns>
    public static CDepCollectInfo DoBuildAssetBundle(string path, UnityEngine.Object asset,
                                                     bool realBuildOrJustPath = true)
    {
        path = Path.ChangeExtension(path, AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt));
        //asset.name = fullAssetPath;
        var hasBuilded = false;

        if (!BuildRecord.ContainsKey(path))
        {
            if (realBuildOrJustPath)
            {
                AddCache(path);
            }
            if (IsJustCollect)
            {
                AddCache(path);
            }
            if (!IsJustCollect && realBuildOrJustPath)
            {
                //BuildedCache[fullAssetPath] = true;
                BuildTools.BuildAssetBundle(asset, path);
                hasBuilded = true;
            }
        }

        return(new CDepCollectInfo
        {
            Path = path,
            Asset = asset,
            HasBuild = hasBuilded,
        });
    }
Exemplo n.º 3
0
        public UIModule()
        {
            var configUiBridge = AppEngine.GetConfig("KEngine.UI", "UIModuleBridge");

            if (!string.IsNullOrEmpty(configUiBridge))
            {
                var uiBridgeTypeName = string.Format("{0}", configUiBridge);
                var uiBridgeType     = KTool.FindType(uiBridgeTypeName);
                if (uiBridgeType != null)
                {
                    UiBridge = Activator.CreateInstance(uiBridgeType) as IUIBridge;
                    Log.Debug("Use UI Bridge: {0}", uiBridgeType);
                }
                else
                {
                    Log.Error("Cannot find UIBridge Type: {0}", uiBridgeTypeName);
                }
            }

            if (UiBridge == null)
            {
                UiBridge = new UGUIBridge();
            }

            UiBridge.InitBridge();
        }
Exemplo n.º 4
0
        public static void MakeCharacterAssetBundleNames()
        {
            var dir = ResourcesBuildDir;

            // set BundleResources's all bundle name
            foreach (var filepath in Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories))
            {
                if (filepath.EndsWith(".meta"))
                {
                    continue;
                }

                var importer = AssetImporter.GetAtPath(filepath);
                if (importer == null)
                {
                    Log.Error("Not found: {0}", filepath);
                    continue;
                }
                if (filepath.Contains("BundleResources/Characters"))
                {
                    var bundleName = filepath.Substring(dir.Length, filepath.Length - dir.Length);
                    importer.assetBundleName = bundleName + AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt);
                }
                else
                {
                    importer.assetBundleName = null;
                }
            }

            Log.Info("Make all asset name successs!");
        }
Exemplo n.º 5
0
        /// <summary>
        /// 收集StringsTalbe.bytes的字符串
        /// </summary>
        /// <param name="refItems"></param>
        static void CollectStringsTable(ref I18NItems refItems)
        {
            var compilePath      = AppEngine.GetConfig("KEngine.Setting", "SettingCompiledPath");
            var ext              = AppEngine.GetConfig("KEngine", "AssetBundleExt");
            var stringsTablePath = string.Format("{0}/StringsTable{1}", compilePath, ext);

            if (!File.Exists(stringsTablePath))
            {
                return;
            }

            string stringsTableContent;

            using (var stream = new FileStream(stringsTablePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (var reader = new StreamReader(stream))
                {
                    stringsTableContent = reader.ReadToEnd();
                }
            }

            var tableFile = new TableFile(stringsTableContent);

            foreach (var row in tableFile)
            {
                var srcStr = row["Id"];
                refItems.Add(srcStr, stringsTablePath);
            }
            Debug.Log("[CollectStringsTable]Success!");
        }
Exemplo n.º 6
0
        public static void AutoMakeUILuaScripts()
        {
            var luaPath = AppEngine.GetConfig("KSFramework.Lua", "LuaPath");

            Debug.Log("Find UI from current scenes, LuaScriptPath: " + luaPath);

            var windowAssets = GameObject.FindObjectsOfType <UIWindowAsset>();

            if (windowAssets.Length > 0)
            {
                foreach (var windowAsset in windowAssets)
                {
                    var uiName     = windowAsset.name;
                    var scriptPath = string.Format("{0}/{1}/UI/UI{2}.lua", KResourceModule.EditorProductFullPath,
                                                   luaPath, uiName);
                    if (!File.Exists(scriptPath))
                    {
                        File.WriteAllText(scriptPath, LuaUITempalteCode.Replace("$UI_NAME", "UI" + uiName));
                        Debug.LogWarning("New Lua Script: " + scriptPath);
                    }
                    else
                    {
                        Debug.Log("Exists Lua Script, ignore: " + scriptPath);
                    }
                }
            }
            else
            {
                Debug.LogError("Not found any `UIWindowAsset` Component");
            }
        }
Exemplo n.º 7
0
        private static void OnPostProcessScene()
        {
            if (!_hasBeforeBuildApp)
            {
                _hasBeforeBuildApp = true;
                // 这里是编译前, 对Lua进行编译处理
                Debug.Log("[LuaModuleEditor]Start compile lua script...");
                var luaPath = AppEngine.GetConfig("KSFramework.Lua", "LuaPath");
                var ext     = AppEngine.GetConfig("KEngine", "AssetBundleExt");

                var luaCount            = 0;
                var editorLuaScriptPath = Path.Combine(KResourceModule.EditorProductFullPath, luaPath);
                editorLuaScriptPath = editorLuaScriptPath.Replace("\\", "/");
                var toDir = "Assets/StreamingAssets/" + luaPath;

                // 所有的Lua脚本拷贝到StreamingAssets
                foreach (var path in Directory.GetFiles(editorLuaScriptPath, "*", SearchOption.AllDirectories))
                {
                    var cleanPath = path.Replace("\\", "/");

                    var relativePath = cleanPath.Replace(editorLuaScriptPath + "/", "");
                    var toPath       = Path.Combine(toDir, relativePath) + ext;

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

                    File.Copy(cleanPath, toPath, true);
                    luaCount++;
                }
                AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
                Debug.Log(string.Format("[LuaModuleEditor]compile lua script count: {0}", luaCount));
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// 惰式初始化
        /// </summary>
        public static void Init()
        {
            if (_isInited)
            {
                return;
            }

            var settingPath   = string.Format("I18N/{0}{1}", Lang, AppEngine.GetConfig(KEngineDefaultConfigs.SettingExt));
            var settingReader = SettingModule.Get(settingPath, false);

            foreach (var row in settingReader)
            {
                Strs[row["Id"]] = row["Value"];
            }

#if UNITY_EDITOR
            // 开发热重载
            if (SettingModule.IsFileSystemMode)
            {
                SettingModule.WatchSetting(settingPath, (_) =>
                {
                    _isInited = false;
                });
            }
#endif
            _isInited = true;
        }
Exemplo n.º 9
0
        public IEnumerator Init()
        {
            var configUiBridge = AppEngine.GetConfig("UIModuleBridge");

            if (!string.IsNullOrEmpty(configUiBridge))
            {
                var uiBridgeTypeName = string.Format("K{0}Bridge", configUiBridge);
                var uiBridgeType     = Type.GetType(uiBridgeTypeName);
                if (uiBridgeType != null)
                {
                    UiBridge = Activator.CreateInstance(uiBridgeType) as IKUIBridge;
                    Logger.Debug("Use UI Bridge: {0}", uiBridgeType);
                }
                else
                {
                    Logger.LogError("Cannot find UIBridge Type: {0}", uiBridgeTypeName);
                }
            }

            if (UiBridge == null)
            {
                UiBridge = new KUGUIBridge();
            }

            UiBridge.InitBridge();

            yield break;
        }
Exemplo n.º 10
0
        private static string GetFileSystemPath(string path)
        {
            var compilePath = AppEngine.GetConfig("KEngine.Setting", "SettingCompiledPath");
            var resPath     = Path.Combine(compilePath, path);

            return(resPath);
        }
Exemplo n.º 11
0
    public static CDepCollectInfo __DoBuildScriptableObject(string fullAssetPath, ScriptableObject so,
                                                            bool realBuildOrJustPath = true)
    {
        var hasBuilded = false;

        fullAssetPath = Path.ChangeExtension(fullAssetPath, AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt));

        if (so == null)
        {
            Log.Error("Error Null ScriptableObject: {0}", fullAssetPath);
        }
        else
        {
            //so.name = fullAssetPath;
            if (!BuildRecord.ContainsKey(fullAssetPath))
            {
                AddCache(fullAssetPath);
                if (!IsJustCollect && realBuildOrJustPath)
                {
                    BuildTools.BuildScriptableObject(so, fullAssetPath);
                    hasBuilded = true;
                }
            }
        }

        return(new CDepCollectInfo
        {
            Path = fullAssetPath,
            Asset = so,
            HasBuild = hasBuilded,
        });
    }
Exemplo n.º 12
0
    /// <summary>
    /// 图片打包工具,直接打包,不用弄成Texture!, 需要借助TexturePacker
    /// </summary>
    /// <summary>
    /// 单独打包的纹理图片, 这种图片,不在Unity目录内,用bytes读取, 指定保存的目录
    /// </summary>
    /// <param name="saveCacheFolderName"></param>
    /// <param name="tex"></param>
    /// <returns></returns>
    public static string BuildIOTexture(string saveCacheFolderName, string imageSystemFullPath, float scale = 1)
    {
        var cleanPath = imageSystemFullPath.Replace("\\", "/");

        var fileName  = Path.GetFileNameWithoutExtension(cleanPath);
        var buildPath = string.Format("{0}/{1}_{0}{2}", saveCacheFolderName, fileName,
                                      AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt));
        var needBuild = AssetVersionControl.TryCheckNeedBuildWithMeta(cleanPath);

        var texture = new Texture2D(1, 1);

        if (needBuild && !IsJustCollect)
        {
            var cacheDir = "Assets/" + KEngineDef.ResourcesBuildCacheDir + "/BuildIOTexture/" + saveCacheFolderName +
                           "/";
            var cacheFilePath = cacheDir + Path.GetFileName(cleanPath);

            //CFolderSyncTool.TexturePackerScaleImage(cleanPath, cacheFilePath, Math.Min(1, GameDef.PictureScale * scale));  // TODO: do scale

            texture = AssetDatabase.LoadAssetAtPath(cacheFilePath, typeof(Texture2D)) as Texture2D;
            if (texture == null)
            {
                Log.Error("[BuildIOTexture]TexturePacker scale failed... {0}", cleanPath);
                return(null);
            }

            //CTextureCompressor.CompressTextureAsset(cleanPath, texture);

            //CTextureCompressor.AutoCompressTexture2D(texture, EditorUserBuildSettings.activeBuildTarget);

            //if (!texture.LoadImage(File.ReadAllBytes(cleanPath)))
            //{
            //    Log.Error("无法LoadImage的Texture: {0}", cleanPath);
            //    return null;
            //}
            //texture.name = fileName;

            //// 多线程快速,图像缩放,双线性过滤插值
            //TextureScaler.Bilinear(texture, (int)(texture.width * GameDef.PictureScale),
            //    (int)(texture.height * GameDef.PictureScale));
            //GC.CollectMaterial();
        }

        // card/xxx_card.box
        var result = KDependencyBuild.DoBuildAssetBundle(buildPath, texture, needBuild);

        if (needBuild)
        {
            AssetVersionControl.TryMarkBuildVersion(cleanPath);
        }

        return(result.Path);
    }
Exemplo n.º 13
0
        private static void OnPostProcessScene()
        {
            if (!_hasBeforeBuildApp && !EditorApplication.isPlayingOrWillChangePlaymode)
            {
                _hasBeforeBuildApp = true;
                // 这里是编译前, Setting目录的配置文件拷贝进去StreamingAssetse
                Debug.Log("[SettingModuleBuildHandler]Start copy settings...");
                var editorLuaScriptPath = AppEngine.GetConfig("KEngine.Setting", "SettingCompiledPath");
                //var ext = AppEngine.GetConfig("KEngine", "AssetBundleExt");

                var luaCount = 0;
                //var editorLuaScriptPath = Path.Combine(KResourceModule.EditorProductFullPath, compilePath);
                editorLuaScriptPath = editorLuaScriptPath.Replace("\\", "/");

                if (!Directory.Exists(editorLuaScriptPath))
                {
                    return;
                }

                var toDir = "Assets/StreamingAssets/" + AppEngine.GetConfig("KEngine.Setting", "SettingResourcesPath"); // 文件夹名称获取

                // 删除所有,确保没冗余
                if (Directory.Exists(toDir))
                {
                    Directory.Delete(toDir, true);
                }

                // 所有的Lua脚本拷贝到StreamingAssets
                foreach (var path in Directory.GetFiles(editorLuaScriptPath, "*", SearchOption.AllDirectories))
                {
                    var cleanPath = path.Replace("\\", "/");

                    var relativePath = cleanPath.Replace(editorLuaScriptPath + "/", "");
                    var toPath       = Path.Combine(toDir, relativePath);

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

                    File.Copy(cleanPath, toPath, true);
                    if (OnCopyFile != null)
                    {
                        OnCopyFile(toPath);
                    }
                    luaCount++;
                }
                AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
                Debug.Log(string.Format("[SettingModuleBuildHandler]compile setting file count: {0}", luaCount));
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// 是否清理所有之前的
        /// </summary>
        /// <param name="remake">Clear all asset bundle name</param>
        public static void DoMakeAssetBundleNames(bool remake)
        {
            var dir = ResourcesBuildDir;

            // Check marked asset bundle whether real
            if (remake)
            {
                foreach (var assetGuid in AssetDatabase.FindAssets(""))
                {
                    EditorUtility.DisplayProgressBar("AssetBundle", string.Format("Finding assets... {0}", assetGuid), .2f);

                    var assetPath     = AssetDatabase.GUIDToAssetPath(assetGuid);
                    var assetImporter = AssetImporter.GetAtPath(assetPath);
                    var bundleName    = assetImporter.assetBundleName;
                    if (string.IsNullOrEmpty(bundleName))
                    {
                        continue;
                    }
                    if (!assetPath.StartsWith(dir))
                    {
                        assetImporter.assetBundleName = null;
                    }
                }
            }
            // set BundleResources's all bundle name
            foreach (var filepath in Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories))
            {
                EditorUtility.DisplayProgressBar("AssetBundle", string.Format("Making asset bundle name: {0}", filepath), .5f);

                if (filepath.EndsWith(".meta"))
                {
                    continue;
                }

                var importer = AssetImporter.GetAtPath(filepath);
                if (importer == null)
                {
                    Log.Error("Not found: {0}", filepath);
                    continue;
                }
                var bundleName = filepath.Substring(dir.Length, filepath.Length - dir.Length);
                importer.assetBundleName = bundleName + AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt);
            }

            Log.Info("Make all asset name successs!");
            EditorUtility.ClearProgressBar();
        }
Exemplo n.º 15
0
        public static void MakeAssetBundleNames()
        {
            var dir = ResourcesBuildDir;

            // Check marked asset bundle whether real
            foreach (var assetGuid in AssetDatabase.FindAssets(""))
            {
                var assetPath     = AssetDatabase.GUIDToAssetPath(assetGuid);
                var assetImporter = AssetImporter.GetAtPath(assetPath);
                var bundleName    = assetImporter.assetBundleName;
                if (string.IsNullOrEmpty(bundleName))
                {
                    continue;
                }
                if (!assetPath.StartsWith(dir))
                {
                    assetImporter.assetBundleName = null;
                }
            }

            // set BundleResources's all bundle name
            foreach (var filepath in Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories))
            {
                if (filepath.EndsWith(".meta"))
                {
                    continue;
                }

                var importer = AssetImporter.GetAtPath(filepath);
                if (importer == null)
                {
                    Log.Error("Not found: {0}", filepath);
                    continue;
                }
                var bundleName = filepath.Substring(dir.Length, filepath.Length - dir.Length);
                importer.assetBundleName = bundleName + AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt);

                bool needBuild = AssetVersionControl.TryCheckNeedBuildWithMeta(filepath);
                if (needBuild)
                {
                    AssetVersionControl.TryMarkBuildVersion(filepath);
                    Debug.Log("version: " + filepath);
                }
            }

            Log.Info("Make all asset name successs!");
        }
Exemplo n.º 16
0
        public static void CompileTabConfigs()
        {
            var sourcePath = SettingSourcePath;//AppEngine.GetConfig("SettingSourcePath");

            if (string.IsNullOrEmpty(sourcePath))
            {
                Logger.LogError("Need to KEngineConfig: SettingSourcePath");
                return;
            }
            var compilePath = AppEngine.GetConfig("SettingPath");

            if (string.IsNullOrEmpty(compilePath))
            {
                Logger.LogError("Need to KEngineConfig: SettingPath");
                return;
            }
            CompileTabConfigs(sourcePath, compilePath, SettingCodePath, SettingExtension);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Get script full path
        /// </summary>
        /// <param name="scriptRelativePath"></param>
        /// <returns></returns>
        string GetScriptPath(string scriptRelativePath)
        {
            var luaPath = AppEngine.GetConfig("KSFramework.Lua", "LuaPath");
            var ext     = AppEngine.GetConfig("KEngine", "AssetBundleExt");

            var relativePath = string.Format("{0}/{1}.lua", luaPath, scriptRelativePath);

            if (Log.IsUnityEditor)
            {
                var editorLuaScriptPath = Path.Combine(KResourceModule.EditorProductFullPath,
                                                       relativePath);

                return(editorLuaScriptPath);
            }

            relativePath += ext;
            return(relativePath);
        }
Exemplo n.º 18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="force">Whether or not,check diff.  false will be faster!</param>
        /// <param name="genCode">Generate static code?</param>
        public static void DoCompileSettings(bool force = true)
        {
            var sourcePath = SettingSourcePath;//AppEngine.GetConfig("SettingSourcePath");

            if (string.IsNullOrEmpty(sourcePath))
            {
                Log.Error("Need to KEngineConfig: SettingSourcePath");
                return;
            }
            var compilePath = AppEngine.GetConfig("KEngine.Setting", "SettingCompiledPath");

            if (string.IsNullOrEmpty(compilePath))
            {
                Log.Error("Need to KEngineConfig: SettingCompiledPath");
                return;
            }
            CompileTabConfigs(sourcePath, compilePath, SettingCodePath, SettingExtension, force);
        }
Exemplo n.º 19
0
        public static void MakeAssetBundleNames()
        {
            var dir = ResourcesBuildDir;

            /*
             * // Check marked asset bundle whether real
             * foreach (var assetGuid in AssetDatabase.FindAssets(""))
             * {
             *  var assetPath = AssetDatabase.GUIDToAssetPath(assetGuid);
             *  var assetImporter = AssetImporter.GetAtPath(assetPath);
             *  var bundleName = assetImporter.assetBundleName;
             *  if (string.IsNullOrEmpty(bundleName))
             *  {
             *      continue;
             *  }
             * //                if (!assetPath.StartsWith(dir))
             * //                {
             * //                    assetImporter.assetBundleName = null;
             * //                }
             * }
             */

            // set BundleResources's all bundle name
            foreach (var filepath in Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories))
            {
                if (filepath.EndsWith(".meta"))
                {
                    continue;
                }

                var importer = AssetImporter.GetAtPath(filepath);
                if (importer == null)
                {
                    Log.Error("Not found: {0}", filepath);
                    continue;
                }
                var bundleName = filepath.Substring(dir.Length, filepath.Length - dir.Length);
                importer.assetBundleName = bundleName + AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt);
            }

            Log.Info("Make all asset name successs!");
        }
Exemplo n.º 20
0
    public IEnumerator LoadUIAsset(CUILoadState openState, UILoadRequest request)
    {
        var name = openState.TemplateName;
        // 具体加载逻辑
        // manifest
        string manifestPath = ResourceDepUtils.GetBuildPath(string.Format("BundleResources/NGUI/{0}.prefab.manifest{1}", name,
                                                                          AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt)));
        var manifestLoader = KBytesLoader.Load(manifestPath, KResourceInAppPathType.PersistentAssetsPath, KAssetBundleLoaderMode.PersitentDataPathSync);

        while (!manifestLoader.IsCompleted)
        {
            yield return(null);
        }
        var manifestBytes = manifestLoader.Bytes;

        manifestLoader.Release(); // 释放掉文本字节
        var utf8NoBom    = new UTF8Encoding(false);
        var manifestList = utf8NoBom.GetString(manifestBytes).Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);

        for (var i = 0; i < manifestList.Length; i++)
        {
            var depPath   = manifestList[i] + AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt);
            var depLoader = KAssetFileLoader.Load(depPath);
            while (!depLoader.IsCompleted)
            {
                yield return(null);
            }
        }
        string path = ResourceDepUtils.GetBuildPath(string.Format("BundleResources/NGUI/{0}.prefab{1}", name, KEngine.AppEngine.GetConfig("AssetBundleExt")));

        var assetLoader = KStaticAssetLoader.Load(path);

        openState.UIResourceLoader = assetLoader; // 基本不用手工释放的
        while (!assetLoader.IsCompleted)
        {
            yield return(null);
        }
        request.Asset = assetLoader.TheAsset;
    }
Exemplo n.º 21
0
        private static void DeleteAssetBundle()
        {
            var sel       = Selection.activeObject;
            var path      = AssetDatabase.GetAssetPath(sel);
            var startWith = "Assets/" + KEngineDef.ResourcesBuildDir + "/";

            if (!path.StartsWith(startWith))
            {
                Debug.LogError("Not Asset Bundle Resources: " + path);
                return;
            }

            var abPath = Path.Combine(KResourceModule.ProductPathWithoutFileProtocol,
                                      KResourceModule.BundlesPathRelative + path.Substring(startWith.Length, path.Length - startWith.Length) + AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt));

            if (File.Exists(abPath))
            {
                Debug.Log("Delete AB: " + abPath);
                File.Delete(abPath);
            }
            else
            {
                Debug.LogError("Not Exist AB: " + abPath);
            }
        }
Exemplo n.º 22
0
 public static string GetBuildRelPath(string uiName)
 {
     return(String.Format("UI/{0}_UI{1}", uiName, AppEngine.GetConfig("KEngine", "AssetBundleExt")));
 }
Exemplo n.º 23
0
        public static void CreateNewUI()
        {
#if UNITY_5 || UNITY_2017_1_OR_NEWER
            var currentScene = EditorSceneManager.GetActiveScene().path;
#else
            var currentScene = EditorApplication.currentScene;
#endif
            GameObject mainCamera = GameObject.Find("Main Camera");
            if (mainCamera != null)
            {
                GameObject.DestroyImmediate(mainCamera);
            }

            var uiName = Path.GetFileNameWithoutExtension(currentScene);
            if (string.IsNullOrEmpty(uiName) || GameObject.Find(uiName) != null) // default use scene name, if exist create random name
            {
                uiName = "NewUI_" + Path.GetRandomFileName();
            }
            GameObject uiObj = new GameObject(uiName);
            uiObj.layer = (int)UnityLayerDef.UI;
            uiObj.AddComponent <UIWindowAsset>();

            var uiPanel = new GameObject("Image").AddComponent <Image>();
            uiPanel.transform.parent = uiObj.transform;
            KTool.ResetLocalTransform(uiPanel.transform);

            var canvas = uiObj.AddComponent <Canvas>();
            canvas.renderMode = RenderMode.ScreenSpaceCamera;
            CanvasScaler canvasScaler = uiObj.AddComponent <CanvasScaler>();
            uiObj.AddComponent <GraphicRaycaster>();
            var uiSize       = new Vector2(1280, 720);
            var uiResolution = AppEngine.GetConfig("KEngine.UI", "UIResolution");
            if (!string.IsNullOrEmpty(uiResolution))
            {
                var sizeArr = uiResolution.Split(',');
                if (sizeArr.Length >= 2)
                {
                    uiSize = new Vector2(sizeArr[0].ToInt32(), sizeArr[1].ToInt32());
                }
            }
            canvasScaler.uiScaleMode         = CanvasScaler.ScaleMode.ScaleWithScreenSize;
            canvasScaler.referenceResolution = uiSize;
            canvasScaler.screenMatchMode     = CanvasScaler.ScreenMatchMode.Expand;

            if (GameObject.Find("EventSystem") == null)
            {
                var evtSystemObj = new GameObject("EventSystem");
                evtSystemObj.AddComponent <EventSystem>();
                evtSystemObj.AddComponent <StandaloneInputModule>();
#if UNITY_4
                evtSystemObj.AddComponent <TouchInputModule>();
#endif
            }

            if (GameObject.Find("Camera") == null)
            {
                GameObject cameraObj = new GameObject("Camera");
                cameraObj.layer = (int)UnityLayerDef.UI;

                Camera camera = cameraObj.AddComponent <Camera>();
                camera.clearFlags       = CameraClearFlags.Skybox;
                camera.depth            = 0;
                camera.backgroundColor  = Color.grey;
                camera.cullingMask      = 1 << (int)UnityLayerDef.UI;
                camera.orthographicSize = 1f;
                camera.orthographic     = true;
                camera.nearClipPlane    = -2f;
                camera.farClipPlane     = 2f;

                camera.gameObject.AddComponent <AudioListener>();
            }

            Selection.activeGameObject = uiObj;
        }
Exemplo n.º 24
0
        /// <summary>
        /// Compile one directory 's all settings, and return behaivour results
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="compilePath"></param>
        /// <param name="genCodeFilePath"></param>
        /// <param name="changeExtension"></param>
        /// <param name="force"></param>
        /// <returns></returns>
        public static List <TableCompileResult> CompileTabConfigs(string sourcePath, string compilePath, string genCodeFilePath, string changeExtension = ".bytes", bool force = false)
        {
            var results        = new List <TableCompileResult>();
            var compileBaseDir = compilePath;
            // excel compiler
            var compiler = new Compiler(new CompilerConfig()
            {
                ConditionVars = CompileSettingConditionVars
            });

            var excelExt = new HashSet <string>()
            {
                ".xls", ".xlsx", ".tsv"
            };
            var findDir = sourcePath;

            try
            {
                var allFiles      = Directory.GetFiles(findDir, "*.*", SearchOption.AllDirectories);
                var allFilesCount = allFiles.Length;
                var nowFileIndex  = -1; // 开头+1, 起始为0
                foreach (var excelPath in allFiles)
                {
                    nowFileIndex++;
                    var ext      = Path.GetExtension(excelPath);
                    var fileName = Path.GetFileNameWithoutExtension(excelPath);
                    if (excelExt.Contains(ext) && !fileName.StartsWith("~")) // ~开头为excel临时文件,不要读
                    {
                        // it's an excel file
                        var relativePath = excelPath.Replace(findDir, "").Replace("\\", "/");
                        if (relativePath.StartsWith("/"))
                        {
                            relativePath = relativePath.Substring(1);
                        }


                        var compileToPath = string.Format("{0}/{1}", compileBaseDir,
                                                          Path.ChangeExtension(relativePath, changeExtension));
                        var srcFileInfo = new FileInfo(excelPath);

                        EditorUtility.DisplayProgressBar("Compiling Excel to Tab...",
                                                         string.Format("{0} -> {1}", excelPath, compileToPath), nowFileIndex / (float)allFilesCount);

                        // 如果已经存在,判断修改时间是否一致,用此来判断是否无需compile,节省时间
                        bool doCompile = true;
                        if (File.Exists(compileToPath))
                        {
                            var toFileInfo = new FileInfo(compileToPath);

                            if (!force && srcFileInfo.LastWriteTime == toFileInfo.LastWriteTime)
                            {
                                //Log.DoLog("Pass!SameTime! From {0} to {1}", excelPath, compileToPath);
                                doCompile = false;
                            }
                        }
                        if (doCompile)
                        {
                            Log.Warning("[SettingModule]Compile from {0} to {1}", excelPath, compileToPath);

                            var compileResult = compiler.Compile(excelPath, compileToPath, compileBaseDir, doCompile);

                            // 添加模板值
                            results.Add(compileResult);

                            var compiledFileInfo = new FileInfo(compileToPath);
                            compiledFileInfo.LastWriteTime = srcFileInfo.LastWriteTime;
                        }
                    }
                }

                // 根据模板生成所有代码,  如果不是强制重建,无需进行代码编译
                if (!AutoGenerateCode)
                {
                    Log.Warning("Ignore Gen Settings code");
                }
                else if (!force)
                {
                    Log.Warning("Ignore Gen Settings Code, not a forcing compiling");
                }
                else
                {
                    // 根据编译结果,构建vars,同class名字的,进行合并
                    var templateVars = new Dictionary <string, TableTemplateVars>();
                    foreach (var compileResult in results)
                    {
                        // 判断本文件是否忽略代码生成,用正则表达式
                        var settingCodeIgnorePattern = AppEngine.GetConfig("KEngine.Setting", "SettingCodeIgnorePattern", false);
                        if (!string.IsNullOrEmpty(settingCodeIgnorePattern))
                        {
                            var ignoreRegex = new Regex(settingCodeIgnorePattern);
                            if (ignoreRegex.IsMatch(compileResult.TabFilePath))
                            {
                                continue; // ignore this
                            }
                        }

                        var customExtraStr = CustomExtraString != null?CustomExtraString(compileResult) : null;

                        var templateVar = new TableTemplateVars(compileResult, customExtraStr);

                        // 尝试类过滤
                        var ignoreThisClassName = false;
                        if (GenerateCodeFilesFilter != null)
                        {
                            for (var i = 0; i < GenerateCodeFilesFilter.Length; i++)
                            {
                                var filterClass = GenerateCodeFilesFilter[i];
                                if (templateVar.ClassName.Contains(filterClass))
                                {
                                    ignoreThisClassName = true;
                                    break;
                                }
                            }
                        }
                        if (!ignoreThisClassName)
                        {
                            if (!templateVars.ContainsKey(templateVar.ClassName))
                            {
                                templateVars.Add(templateVar.ClassName, templateVar);
                            }
                            else
                            {
                                templateVars[templateVar.ClassName].Paths.Add(compileResult.TabFilePath);
                            }
                        }
                    }

                    // 整合成字符串模版使用的List
                    var templateHashes = new List <Hash>();
                    foreach (var kv in templateVars)
                    {
                        var templateVar        = kv.Value;
                        var renderTemplateHash = Hash.FromAnonymousObject(templateVar);
                        templateHashes.Add(renderTemplateHash);
                    }


                    var nameSpace = "AppSettings";
                    GenerateCode(genCodeFilePath, nameSpace, templateHashes);
                }
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }
            return(results);
        }
Exemplo n.º 25
0
 private string GetConfValue(string key)
 {
     return(AppEngine.GetConfig(key));
 }
Exemplo n.º 26
0
        /// <summary>
        /// ResourceDep系统专用的打包AssetBundle函数
        /// </summary>
        /// <param name="asset"></param>
        /// <param name="path"></param>
        /// <param name="depFileRelativeBuildPath">依赖文件列表,相对的AssetBundle打包路径</param>
        /// <param name="buildTarget"></param>
        /// <param name="quality"></param>
        /// <returns></returns>
        private static BuildBundleResult BuildAssetBundle(Object asset, string path,
                                                          IList <string> depFileRelativeBuildPath, BuildTarget buildTarget, KResourceQuality quality)
        {
            //是否是Level / Scene
            var isScene = asset.ToString().Contains("SceneAsset");

            uint crc  = 0;
            var  time = DateTime.Now;
            // 最终完整路径
            var buildToFullPath = BuildTools.MakeSureExportPath(path, buildTarget, quality) +
                                  AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt);
            var buildToRelativePath = AbsPath2RelativePath(buildToFullPath);//buildToFullPath.Replace(workdirPath, "").Substring(1); // 转换成相对路径,避免路径过程无法打包的问题

            var assetPath = AssetDatabase.GetAssetPath(asset);

            // 版本标记
            var unityAssetType = GetUnityAssetType(assetPath);

            if (unityAssetType == UnityAssetType.Builtin || unityAssetType == UnityAssetType.Memory)
            {
                var buildAssetPath = GetBuildAssetPath(asset);
                AssetVersionControl.TryMarkRecord(buildAssetPath);
                BuildedPool.Add(buildAssetPath);
            }
            else
            {
                AssetVersionControl.TryMarkBuildVersion(assetPath);
                BuildedPool.Add(assetPath);
            }

            bool result = false;

            if (isScene)
            {
                var resultStr = BuildPipeline.BuildStreamedSceneAssetBundle(new string[] { assetPath }, buildToRelativePath,
                                                                            buildTarget, out crc);
                result = String.IsNullOrEmpty(resultStr);
                if (!String.IsNullOrEmpty(resultStr))
                {
                    Debug.LogError(resultStr);
                }
            }
            else
            {
                result = BuildPipeline.BuildAssetBundle(asset, null, buildToRelativePath,
                                                        out crc,
                                                        BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.DeterministicAssetBundle |
                                                        BuildAssetBundleOptions.CompleteAssets,
                                                        buildTarget);
            }

            // 创建依赖记录文件
            string fullManifestPath = null;

            //if (depFileRelativeBuildPath != null && depFileRelativeBuildPath.Any())
            {
                //var manifestFileContent = string.Join("\n", depFileRelativeBuildPath.KToArray());
                if (depFileRelativeBuildPath == null)
                {
                    depFileRelativeBuildPath = new List <string>();
                }

                var manifestPath = path + ".manifest";
                fullManifestPath = BuildTools.MakeSureExportPath(manifestPath, buildTarget, quality) +
                                   AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt);
                var relativeManifestPath = AbsPath2RelativePath(fullManifestPath); // 转成相对路径

                var utf8NoBom = new UTF8Encoding(false);
                //try
                //{
                File.WriteAllLines(relativeManifestPath, depFileRelativeBuildPath.KToArray(), utf8NoBom);
                //}
                //catch (Exception e)
                //{
                //    // 会出现DirectoryNotFound,但是目录明明就存在! 先Catch
                //    Log.Error("Exception: {0}", e.Message);
                //    var dirPath = Path.GetDirectoryName(fullManifestPath);
                //    if (Directory.Exists(dirPath))
                //        Log.Error("Directory Exists: {0}", dirPath);
                //    else
                //    {
                //        Log.Error("Directory not exists: {0}", dirPath);
                //    }
                //}
            }

            if (result)
            {
                var abInfo = new FileInfo(buildToFullPath);
                Log.Info("Build AssetBundle: {0} / CRC: {1} / Time: {2:F4}s / Size: {3:F3}KB / FullPath: {4} / RelPath: {5}", path, crc, (DateTime.Now - time).TotalSeconds,
                         abInfo.Length / 1024d, buildToFullPath, buildToRelativePath);
            }
            else
            {
                Log.Error("生成文件失败: {0}, crc: {1} 耗时: {2:F5}, 完整路径: {3}", path, crc,
                          (DateTime.Now - time).TotalSeconds, buildToFullPath);
            }
            return(new BuildBundleResult
            {
                Crc = crc,
                FullPath = buildToFullPath,
                RelativePath = path,
                IsSuccess = result,
                ManifestFullPath = fullManifestPath,
            });
        }
Exemplo n.º 27
0
        private static IEnumerator CoLoadAssetBundleAsync(string relativePath, ResourceDepRequest request)
        {
            // manifest
            string manifestPath = ResourceDepUtils.GetBuildPath(String.Format("{0}.manifest{1}", relativePath,
                                                                              AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt)));
            var manifestLoader = KBytesLoader.Load(manifestPath, LoaderMode.Sync);

            while (!manifestLoader.IsCompleted)
            {
                yield return(null);
            }

            // manifest读取失败,可能根本没有manifest,是允许的
            if (manifestLoader.IsSuccess)
            {
                var manifestBytes = manifestLoader.Bytes;
                manifestLoader.Release(); // 释放掉文本字节
                string[] manifestList = GetManifestList(manifestBytes);
                for (var i = 0; i < manifestList.Length; i++)
                {
                    var depPath   = manifestList[i] + AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt);
                    var depLoader = KAssetFileLoader.Load(depPath);
                    if (request.Loaders == null)
                    {
                        request.Loaders = new List <KAbstractResourceLoader>();
                    }
                    request.Loaders.Add(depLoader);
                    while (!depLoader.IsCompleted)
                    {
                        yield return(null);
                    }
                }
            }
            string path =
                GetBuildPath(String.Format("{0}{1}", relativePath,
                                           AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt)));

            // 获取后缀名
            var ext = Path.GetExtension(relativePath);

            if (ext == ".unity" || ext == ".shader")
            {
                // Scene
                var sceneLoader = KAssetBundleLoader.Load(path);

                if (request.Loaders == null)
                {
                    request.Loaders = new List <KAbstractResourceLoader>();
                }
                request.Loaders.Add(sceneLoader);
                while (!sceneLoader.IsCompleted)
                {
                    yield return(null);
                }
            }
            else
            {
                var assetLoader = KAssetFileLoader.Load(path);
                while (!assetLoader.IsCompleted)
                {
                    yield return(null);
                }
                request.Asset = assetLoader.Asset;
            }

            request.IsDone = true;
        }
Exemplo n.º 28
0
        /// <summary>
        /// 同步加载AssetBundle
        /// </summary>
        /// <param name="relativePath"></param>
        /// <returns></returns>
        public static Object LoadAssetBundleSync(string relativePath)
        {
            //CheckLoadShadersPrefab();
            // manifest
            string manifestPath = ResourceDepUtils.GetBuildPath(String.Format("{0}.manifest{1}", relativePath,
                                                                              AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt)));
            var manifestLoader = KBytesLoader.Load(manifestPath, LoaderMode.Sync);
            //while (!manifestLoader.IsCompleted)
            //    yield return null;
            var manifestBytes = manifestLoader.Bytes;

            manifestLoader.Release(); // 释放掉文本字节
            if (manifestBytes != null)
            {
                var manifestList = GetManifestList(manifestBytes);
                for (var i = 0; i < manifestList.Length; i++)
                {
                    var depPath = manifestList[i] + AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt);
                    //var depLoader =
                    KAssetFileLoader.Load(depPath);
                    //while (!depLoader.IsCompleted)
                    //{
                    //    yield return null;
                    //}

                    /*if (Application.isEditor)
                     * {
                     *  Log.Info("Load dep sync:{0}, from: {1}", depPath, relativePath);
                     * }*/
                }
            }
            else
            {
                Log.Warning("Cannot find Manifest: {0}", relativePath);
            }

            string path =
                GetBuildPath(String.Format("{0}{1}", relativePath,
                                           AppEngine.GetConfig(KEngineDefaultConfigs.AssetBundleExt)));

            //while (!assetLoader.IsCompleted)
            //    yield return null;
            // 获取后缀名
            var ext = Path.GetExtension(relativePath);

            if (ext == ".unity" || ext == ".shader")
            {
                // Scene
                //var sceneLoader =
                KAssetBundleLoader.Load(path);
                //while (!sceneLoader.IsCompleted)
                //    yield return null;
                return(null);
            }
            else
            {
                var assetLoader = KAssetFileLoader.Load(path);
                //while (!assetLoader.IsCompleted)
                //    yield return null;
                return(assetLoader.Asset);
            }
        }