Esempio n. 1
0
    public virtual bool Execute()
    {
        Logger = new BuildLogger
        {
            BuildEngine = BuildEngine,
        };

        Logger.LogInfo(string.Format("Fody (version {0}) Executing", typeof(Processor).Assembly.GetName().Version));

        var stopwatch = Stopwatch.StartNew();

        try
        {
            Inner();
            return(!Logger.ErrorOccurred);
        }
        catch (Exception exception)
        {
            Logger.LogException(exception);
            return(false);
        }
        finally
        {
            Logger.LogInfo(string.Format("  Finished Fody {0}ms.", stopwatch.ElapsedMilliseconds));
        }
    }
Esempio n. 2
0
        private static void Dispose(IEnumerable <IContextObject> contextObjects, IEnumerable <IBuildTask> tasks)
        {
            foreach (var disposable in contextObjects.OfType <IDisposable>())
            {
                try
                {
                    disposable.Dispose();
                }
                catch (Exception e)
                {
                    BuildLogger.LogException(e);
                }
            }

            // ReSharper disable once SuspiciousTypeConversion.Global
            foreach (var disposable in tasks.OfType <IDisposable>())
            {
                try
                {
                    disposable.Dispose();
                }
                catch (Exception e)
                {
                    BuildLogger.LogException(e);
                }
            }
        }
Esempio n. 3
0
    public bool Execute()
    {
        var executingMessage = string.Format("Fody (version {0}) Executing", typeof (Processor).Assembly.GetName().Version);
        BuildEngine.LogMessageEvent(new BuildMessageEventArgs(executingMessage, "", "Fody", MSMessageEnum.High));

        var stopwatch = Stopwatch.StartNew();

        Logger = new BuildLogger
                     {
                         BuildEngine = BuildEngine,
                     };

        try
        {
            Inner();
            return !Logger.ErrorOccurred;
        }
        catch (Exception exception)
        {
            Logger.LogException(exception);
            return false;
        }
        finally
        {
            var finishedMessage = string.Format("\tFinished Fody {0}ms.", stopwatch.ElapsedMilliseconds);
            BuildEngine.LogMessageEvent(new BuildMessageEventArgs(finishedMessage, "", "Fody", MSMessageEnum.High));
        }
    }
Esempio n. 4
0
    public bool Execute()
    {
        var executingMessage = string.Format("Fody (version {0}) Executing", typeof(Processor).Assembly.GetName().Version);

        BuildEngine.LogMessageEvent(new BuildMessageEventArgs(executingMessage, "", "Fody", MSMessageEnum.High));

        var stopwatch = Stopwatch.StartNew();

        Logger = new BuildLogger
        {
            BuildEngine = BuildEngine,
        };

        try
        {
            Inner();
            return(!Logger.ErrorOccurred);
        }
        catch (Exception exception)
        {
            Logger.LogException(exception);
            return(false);
        }
        finally
        {
            var finishedMessage = string.Format("\tFinished Fody {0}ms.", stopwatch.ElapsedMilliseconds);
            BuildEngine.LogMessageEvent(new BuildMessageEventArgs(finishedMessage, "", "Fody", MSMessageEnum.High));
        }
    }
Esempio n. 5
0
        /// <summary>
        /// Basic run implementation that takes a set of tasks, a context, and runs returning the build results.
        /// <seealso cref="IBuildTask"/>, <seealso cref="IBuildContext"/>, and <seealso cref="ReturnCode"/>
        /// </summary>
        /// <param name="pipeline">The set of build tasks to run.</param>
        /// <param name="context">The build context to use for this run.</param>
        /// <returns>Return code with status information about success or failure causes.</returns>
        public static ReturnCode Run(IList <IBuildTask> pipeline, IBuildContext context)
        {
            // Avoid throwing exceptions in here as we don't want them bubbling up to calling user code
            if (pipeline == null)
            {
                BuildLogger.LogException(new ArgumentNullException("pipeline"));
                return(ReturnCode.Exception);
            }

            // Avoid throwing exceptions in here as we don't want them bubbling up to calling user code
            if (context == null)
            {
                BuildLogger.LogException(new ArgumentNullException("context"));
                return(ReturnCode.Exception);
            }

            IProgressTracker tracker;

            if (context.TryGetContextObject(out tracker))
            {
                tracker.TaskCount = pipeline.Count;
            }

            context.TryGetContextObject(out IBuildLogger logger);

            foreach (IBuildTask task in pipeline)
            {
                {
                    try
                    {
                        if (!tracker.UpdateTaskUnchecked(task.GetType().Name.HumanReadable()))
                        {
                            return(ReturnCode.Canceled);
                        }

                        ContextInjector.Inject(context, task);
                        ReturnCode result;
                        using (logger.ScopedStep(LogLevel.Info, task.GetType().Name))
                            result = task.Run();
                        if (result < ReturnCode.Success)
                        {
                            return(result);
                        }
                        ContextInjector.Extract(context, task);
                    }
                    catch (Exception e)
                    {
                        BuildLogger.LogError("Build Task {0} failed with exception:\n{1}\n{2}", task.GetType().Name, e.Message, e.StackTrace);
                        return(ReturnCode.Exception);
                    }
                }
            }

            return(ReturnCode.Success);
        }
Esempio n. 6
0
        /// <summary>
        /// Basic run implementation that takes a set of tasks, a context, and runs returning the build results.
        /// <seealso cref="IBuildTask"/>, <seealso cref="IBuildContext"/>, and <seealso cref="ReturnCode"/>
        /// </summary>
        /// <param name="pipeline">The set of build tasks to run.</param>
        /// <param name="context">The build context to use for this run.</param>
        /// <returns>Return code with status information about success or failure causes.</returns>
        public static ReturnCode Run(IList <IBuildTask> pipeline, IBuildContext context)
        {
            // Avoid throwing exceptions in here as we don't want them bubbling up to calling user code
            if (pipeline == null)
            {
                BuildLogger.LogException(new ArgumentNullException("pipeline"));
                return(ReturnCode.Exception);
            }

            // Avoid throwing exceptions in here as we don't want them bubbling up to calling user code
            if (context == null)
            {
                BuildLogger.LogException(new ArgumentNullException("context"));
                return(ReturnCode.Exception);
            }

            IProgressTracker tracker;

            if (context.TryGetContextObject(out tracker))
            {
                tracker.TaskCount = pipeline.Count;
            }

            foreach (IBuildTask task in pipeline)
            {
                try
                {
                    if (!tracker.UpdateTaskUnchecked(task.GetType().Name.HumanReadable()))
                    {
                        return(ReturnCode.Canceled);
                    }

                    ContextInjector.Inject(context, task);
                    var result = task.Run();
                    if (result < ReturnCode.Success)
                    {
                        return(result);
                    }
                    ContextInjector.Extract(context, task);
                }
                catch (Exception e)
                {
                    BuildLogger.LogException(e);
                    return(ReturnCode.Exception);
                }
            }

            return(ReturnCode.Success);
        }
Esempio n. 7
0
 /// <summary>
 /// 取得实例.
 /// </summary>
 /// <returns>实例.</returns>
 /// <param name="iHuaweiDir">华为路径.</param>
 /// <param name="iGameName">游戏名.</param>
 public static HuaweiManifest GetInstance(string iHuaweiDir, string iGameName = null)
 {
     try {
         if (_instance == null)
         {
             _instance = new HuaweiManifest();
         }
         if (false == _instance.InitByHuaweiDir(iHuaweiDir, iGameName))
         {
             _instance = null;
         }
     } catch (Exception e) {
         BuildLogger.LogException("[HuaweiManifest Create Failed] Exeption : {0}",
                                  e.Message);
         _instance = null;
     }
     return(_instance);
 }
Esempio n. 8
0
        /// <summary>
        /// 取得指定目录文件列表(包含子目录).
        /// </summary>
        /// <returns>文件列表.</returns>
        /// <param name="iDirection">文件目录.</param>
        static List <string> GetAllFiles(string iDirection)
        {
            List <string> filesList = new List <string>();

            try
            {
                bool isDir = false;
                if ((false == string.IsNullOrEmpty(iDirection)) &&
                    (true == iDirection.EndsWith("/")))
                {
                    isDir = true;
                }
                if (true == isDir)
                {
                    string[] files = Directory.GetFiles(iDirection, "*.*", SearchOption.AllDirectories);

                    foreach (string strVal in files)
                    {
                        if (string.IsNullOrEmpty(strVal))
                        {
                            continue;
                        }
                        if (strVal.EndsWith(".ds_store") == true)
                        {
                            continue;
                        }
                        filesList.Add(strVal);
                    }
                }
                else
                {
                    filesList.Add(iDirection);
                }
            }
            catch (System.IO.DirectoryNotFoundException exp)
            {
                BuildLogger.LogException("The Directory is not exist!!!(dir:{0} detail:{1})",
                                         iDirection, exp.Message);
            }

            return(filesList);
        }
Esempio n. 9
0
    public virtual bool Execute()
    {
        Logger.LogInfo($"Fody (version {typeof (Processor).Assembly.GetName().Version}) Executing");

        var stopwatch = Stopwatch.StartNew();

        try
        {
            Inner();
            return(!Logger.ErrorOccurred);
        }
        catch (Exception exception)
        {
            Logger.LogException(exception);
            return(false);
        }
        finally
        {
            Logger.LogInfo($"  Finished Fody {stopwatch.ElapsedMilliseconds}ms.");
        }
    }
        /// <summary>
        /// Default implementation of generating Asset Bundles using the Scriptable Build Pipeline.
        /// </summary>
        /// <param name="parameters">Set of parameters used for building asset bundles.</param>
        /// <param name="content">Set of content and explicit asset bundle layout to build.</param>
        /// <param name="result">Results from building the content and explicit asset bundle layout.</param>
        /// <param name="taskList">Custom task list for building asset bundles.</param>
        /// <param name="contextObjects">Additional context objects to make available to the build.</param>
        /// <returns>Return code with status information about success or failure causes.</returns>
        public static ReturnCode BuildAssetBundles(IBundleBuildParameters parameters, IBundleBuildContent content, out IBundleBuildResults result, IList <IBuildTask> taskList, params IContextObject[] contextObjects)
        {
            // Avoid throwing exceptions in here as we don't want them bubbling up to calling user code
            if (parameters == null)
            {
                result = null;
                BuildLogger.LogException(new ArgumentNullException("parameters"));
                return(ReturnCode.Exception);
            }

            // Avoid throwing exceptions in here as we don't want them bubbling up to calling user code
            if (taskList.IsNullOrEmpty())
            {
                result = null;
                BuildLogger.LogException(new ArgumentException("Argument cannot be null or empty.", "taskList"));
                return(ReturnCode.Exception);
            }

            // Don't run if there are unsaved changes
            if (ValidationMethods.HasDirtyScenes())
            {
                result = null;
                return(ReturnCode.UnsavedChanges);
            }

            AssetDatabase.SaveAssets();

            ReturnCode exitCode;

            result = new BundleBuildResults();

            //    using (new SceneStateCleanup())
            using (new BuildInterfacesWrapper())
                using (var progressTracker = new ProgressTracker())
                    using (var buildCache = new BuildCache(parameters.CacheServerHost, parameters.CacheServerPort))
                    {
                        Directory.CreateDirectory(parameters.TempOutputFolder);

                        BuildContext buildContext;
                        try
                        {
                            buildContext = new BuildContext(contextObjects);
                            buildContext.SetContextObject(parameters);
                            buildContext.SetContextObject(content);
                            buildContext.SetContextObject(result);
                            buildContext.SetContextObject(progressTracker);
                            buildContext.SetContextObject(buildCache);
                            buildContext.SetContextObject(new Unity5PackedIdentifiers());
                            buildContext.SetContextObject(new BuildDependencyData());
                            buildContext.SetContextObject(new BundleWriteData());
                            buildContext.SetContextObject(BuildCallbacks);
                        }
                        catch (Exception e)
                        {
                            // Avoid throwing exceptions in here as we don't want them bubbling up to calling user code
                            result = null;
                            BuildLogger.LogException(e);
                            return(ReturnCode.Exception);
                        }

                        exitCode = BuildTasksRunner.Validate(taskList, buildContext);
                        if (exitCode >= ReturnCode.Success)
                        {
                            exitCode = BuildTasksRunner.Run(taskList, buildContext);
                        }

                        if (Directory.Exists(parameters.TempOutputFolder))
                        {
                            Directory.Delete(parameters.TempOutputFolder, true);
                        }
                    }
            return(exitCode);
        }
Esempio n. 11
0
        /// <summary>
        /// Default implementation of generating Asset Bundles using the Scriptable Build Pipeline.
        /// </summary>
        /// <param name="parameters">Set of parameters used for building asset bundles.</param>
        /// <param name="content">Set of content and explicit asset bundle layout to build.</param>
        /// <param name="result">Results from building the content and explicit asset bundle layout.</param>
        /// <param name="taskList">Custom task list for building asset bundles.</param>
        /// <param name="contextObjects">Additional context objects to make available to the build.</param>
        /// <returns>Return code with status information about success or failure causes.</returns>
        public static ReturnCode BuildAssetBundles(IBundleBuildParameters parameters, IBundleBuildContent content, out IBundleBuildResults result, IList <IBuildTask> taskList, params IContextObject[] contextObjects)
        {
            // Avoid throwing exceptions in here as we don't want them bubbling up to calling user code
            if (parameters == null)
            {
                result = null;
                BuildLogger.LogException(new ArgumentNullException("parameters"));
                return(ReturnCode.Exception);
            }

            // Avoid throwing exceptions in here as we don't want them bubbling up to calling user code
            if (taskList.IsNullOrEmpty())
            {
                result = null;
                BuildLogger.LogException(new ArgumentException("Argument cannot be null or empty.", "taskList"));
                return(ReturnCode.Exception);
            }

            // Don't run if there are unsaved changes
            if (ValidationMethods.HasDirtyScenes())
            {
                result = null;
                return(ReturnCode.UnsavedChanges);
            }

            AssetDatabase.SaveAssets();

            ReturnCode exitCode;

            result = new BundleBuildResults();

            using (new BuildInterfacesWrapper())
#if !CI_TESTRUNNER_PROJECT
                using (new SceneStateCleanup())
                    using (var progressTracker = new ProgressTracker())
#else
                using (var progressTracker = new ProgressLoggingTracker())
#endif
                        using (var buildCache = new BuildCache(parameters.CacheServerHost, parameters.CacheServerPort))
                        {
                            Directory.CreateDirectory(parameters.TempOutputFolder);

                            BuildContext buildContext;
                            try
                            {
                                buildContext = new BuildContext(contextObjects);
                                buildContext.SetContextObject(parameters);
                                buildContext.SetContextObject(content);
                                buildContext.SetContextObject(result);
                                buildContext.SetContextObject(progressTracker);
                                buildContext.SetContextObject(buildCache);
                                // If IDeterministicIdentifiers was passed in with contextObjects, don't add the default
                                if (!buildContext.ContainsContextObject(typeof(IDeterministicIdentifiers)))
                                {
                                    buildContext.SetContextObject(new Unity5PackedIdentifiers());
                                }
                                buildContext.SetContextObject(new BuildDependencyData());
                                buildContext.SetContextObject(new BundleWriteData());
                                buildContext.SetContextObject(BuildCallbacks);
                            }
                            catch (Exception e)
                            {
                                // Avoid throwing exceptions in here as we don't want them bubbling up to calling user code
                                result = null;
                                BuildLogger.LogException(e);
                                return(ReturnCode.Exception);
                            }

                            exitCode = BuildTasksRunner.Validate(taskList, buildContext);
                            if (exitCode >= ReturnCode.Success)
#if SBP_PROFILER_ENABLE
                            { exitCode = BuildTasksRunner.RunProfiled(taskList, buildContext); }
#else
                            { exitCode = BuildTasksRunner.Run(taskList, buildContext); }
#endif

                            if (Directory.Exists(parameters.TempOutputFolder))
                            {
                                Directory.Delete(parameters.TempOutputFolder, true);
                            }
                        }


            int  maximumSize      = EditorPrefs.GetInt("BuildCache.maximumSize", 200);
            long maximumCacheSize = maximumSize * 1073741824L; // gigabytes to bytes
            ThreadPool.QueueUserWorkItem(PruneCache, maximumCacheSize);
            return(exitCode);
        }
Esempio n. 12
0
        /// <summary>
        /// 打包资源文件
        /// </summary>
        /// <param name="buildTarget">Build target.</param>
        /// <param name="needCompress">If set to <c>true</c> need compress.</param>
        private static void BuildAssetBundle(BuildTarget buildTarget, bool needCompress = false)
        {
            const string funcBlock = "AssetBundlesBuild.BuildAssetBundle()";

            BuildLogger.OpenBlock(funcBlock);

            // 设置上传的打包类型
            UploadList.GetInstance().BuildTarget = buildTarget.ToString();

            BundlesConfig bcConfig = BundlesConfig.GetInstance();

            if ((null == bcConfig) || (0 >= bcConfig.Resources.Count))
            {
                BuildLogger.LogError("BuildAssetBundle::BundlesConfig is invalid!!!");
                return;
            }

            // 清空依赖关系列表
            BundlesMap bundlesMap = BundlesMap.GetInstance();

            if (null == bundlesMap)
            {
                BuildLogger.LogError("BuildAssetBundle::bundlesMap is invalid!!!");
                return;
            }
            bundlesMap.Clear();

            List <BundleResource> allConfig = bcConfig.Resources;

            // make bundle config
            foreach (BundleResource bc in allConfig)
            {
                // filter file
                if (bc.Mode == BundleMode.OneDir)
                {
                    string    bundleId = BundlesMap.GetBundleID(bc.Path);
                    BundleMap bm       = bundlesMap.GetOrCreateBundlesMap(bundleId);

                    bm.ID   = bundleId;
                    bm.Path = bc.Path;

                    // 取得当前目录的文件列表
                    List <string> files = GetAllFiles(bc.Path);

                    // 遍历文件列表
                    foreach (string file in files)
                    {
                        // .DS_Store文件
                        if (file.EndsWith(".DS_Store") == true)
                        {
                            continue;
                        }
                        // *.meta文件
                        if (file.EndsWith(".meta") == true)
                        {
                            continue;
                        }

                        // 若为忽略文件,则跳过
                        if (bcConfig.isIgnoreFile(bc, file) == true)
                        {
                            bm.RemoveIgnorFile(file);
                            continue;
                        }
                        bm.AddFile(file);
                    }

                    bundlesMap.Maps.Add(bm);
                }
                else if (bc.Mode == BundleMode.SceneOneToOne)
                {
                    // 取得当前目录的文件列表
                    List <string> files = GetAllFiles(bc.Path);

                    foreach (string file in files)
                    {
                        // .DS_Store文件
                        if (file.EndsWith(".DS_Store") == true)
                        {
                            continue;
                        }
                        // *.meta文件
                        if (file.EndsWith(".meta") == true)
                        {
                            continue;
                        }
                        // 若非场景文件,则跳过
                        if (file.EndsWith(".unity") == false)
                        {
                            continue;
                        }

                        // 若为忽略文件,则跳过
                        string    bundleId = BundlesMap.GetBundleID(file);
                        BundleMap bm       = bundlesMap.GetOrCreateBundlesMap(bundleId);
                        if (bcConfig.isIgnoreFile(bc, file) == true)
                        {
                            bm.RemoveIgnorFile(file);
                            continue;
                        }

                        bm.ID   = bundleId;
                        bm.Path = bc.Path;
                        bm.Type = TBundleType.Scene;
                        bm.AddFile(file);

                        bundlesMap.Maps.Add(bm);
                    }
                }
                else if (bc.Mode == BundleMode.FileOneToOne)
                {
                    // 取得当前目录的文件列表
                    List <string> files = GetAllFiles(bc.Path);

                    foreach (string file in files)
                    {
                        // .DS_Store文件
                        if (file.EndsWith(".DS_Store") == true)
                        {
                            continue;
                        }
                        // *.meta文件
                        if (file.EndsWith(".meta") == true)
                        {
                            continue;
                        }

                        // 若为忽略文件,则跳过
                        string    bundleId = BundlesMap.GetBundleID(file);
                        BundleMap bm       = bundlesMap.GetOrCreateBundlesMap(bundleId);
                        if (bcConfig.isIgnoreFile(bc, file) == true)
                        {
                            bm.RemoveIgnorFile(file);
                            continue;
                        }

                        bm.ID   = bundleId;
                        bm.Path = bc.Path;
                        bm.AddFile(file);

                        bundlesMap.Maps.Add(bm);
                    }
                }
                else if (bc.Mode == BundleMode.TopDirOneToOne)
                {
                    // 取得目录列表
                    string[] directories = Directory.GetDirectories(bc.Path);
                    if ((directories == null) || (directories.Length <= 0))
                    {
                        BuildLogger.LogWarning("The no subfolder in this path!!!(dir:{0})",
                                               bc.Path);
                        continue;
                    }

                    foreach (string dir in directories)
                    {
                        // 取得当前目录的文件列表
                        List <string> files = GetAllFiles(dir);

                        string bundleId = BundlesMap.GetBundleID(dir);
                        bundleId = BundlesMap.GetBundleID(dir);
                        if (string.IsNullOrEmpty(bundleId) == true)
                        {
                            continue;
                        }
                        BundleMap bm = bundlesMap.GetOrCreateBundlesMap(bundleId);
                        bm.ID   = bundleId;
                        bm.Path = bc.Path;

                        foreach (string file in files)
                        {
                            // .DS_Store文件
                            if (file.EndsWith(".DS_Store") == true)
                            {
                                continue;
                            }
                            // *.meta文件
                            if (file.EndsWith(".meta") == true)
                            {
                                continue;
                            }

                            // 若为忽略文件,则跳过
                            if (bcConfig.isIgnoreFile(bc, file) == true)
                            {
                                bm.RemoveIgnorFile(file);
                                continue;
                            }

                            bm.AddFile(file);
                        }

                        bundlesMap.Maps.Add(bm);
                    }
                }
            }

            // 目录检测
            string checkDir = UploadList.GetInstance().BundlesOutputDir;

            if (Directory.Exists(checkDir) == false)
            {
                Directory.CreateDirectory(checkDir);
            }
            checkDir = UploadList.GetInstance().BundlesOutputDirOfNormal;
            if (Directory.Exists(checkDir) == false)
            {
                Directory.CreateDirectory(checkDir);
            }
            checkDir = UploadList.GetInstance().BundlesOutputDirOfScene;
            if (Directory.Exists(checkDir) == false)
            {
                Directory.CreateDirectory(checkDir);
            }

            bool successed             = false;
            AssetBundleManifest result = null;

            string[]           allAssets = null;
            AssetBundleBuild[] targets   = null;

            // 一般Bundles
            try {
                targets = bundlesMap.GetAllNormalBundleTargets();
                BuildAssetBundleOptions options = BuildAssetBundleOptions.UncompressedAssetBundle;
                result = BuildPipeline.BuildAssetBundles(
                    UploadList.GetInstance().BundlesOutputDirOfNormal,
                    targets,
                    options,
                    buildTarget);
                BuildLogger.LogMessage(" -> BuildPipeline.BuildAssetBundles");
                if (result != null)
                {
                    allAssets = result.GetAllAssetBundles();
                    if ((allAssets != null) && (targets.Length == allAssets.Length))
                    {
                        successed = true;
                    }
                }
            } catch (Exception exp) {
                BuildLogger.LogException("BuildAssetBundles Detail : {0}", exp.Message);
                successed = false;
            }

            // 更新导出标志位
            if (successed == true)
            {
                BuildLogger.LogMessage(" -> BundlesConfig.UpdateBundleStateWhenCompleted");

                Dictionary <string, string> hashCodes = new Dictionary <string, string>();
                foreach (string asset in allAssets)
                {
                    Hash128 hashCode = result.GetAssetBundleHash(asset);
                    if (string.IsNullOrEmpty(hashCode.ToString()) == true)
                    {
                        continue;
                    }
                    string fileSuffix = UploadList.GetInstance().FileSuffix;
                    string key        = asset;
                    if (string.IsNullOrEmpty(fileSuffix) == false)
                    {
                        fileSuffix = fileSuffix.ToLower();
                        fileSuffix = string.Format(".{0}", fileSuffix);
                        key        = key.Replace(fileSuffix, "");
                    }
                    hashCodes[key] = hashCode.ToString();
                }
                // 初始化检测信息(Hash Code)
                bundlesMap.UpdateUploadList(TBundleType.Normal, hashCodes);
                BuildLogger.LogMessage(" -> BundlesMap.UpdateUploadList Normal");
            }

            // Scene Bundles
            List <SceneBundleInfo> targetScenes = bundlesMap.GetAllSceneBundleTargets();

            if ((targetScenes != null) && (targetScenes.Count > 0))
            {
                foreach (SceneBundleInfo scene in targetScenes)
                {
                    if ((scene == null) ||
                        (scene.GetAllTargets() == null) ||
                        (scene.GetAllTargets().Length <= 0))
                    {
                        continue;
                    }
                    try {
                        BuildOptions options = BuildOptions.BuildAdditionalStreamedScenes;
                        if (TBuildMode.Debug == BuildInfo.GetInstance().BuildMode)
                        {
                            options |= BuildOptions.Development;
                        }
                        string sceneState = BuildPipeline.BuildPlayer(
                            scene.GetAllTargets(),
                            UploadList.GetLocalSceneBundleFilePath(scene.BundleId),
                            buildTarget,
                            options);
                        BuildLogger.LogMessage(" -> BuildPipeline.BuildStreamedSceneAssetBundle(State:{0})", sceneState);
                    } catch (Exception exp) {
                        BuildLogger.LogException("BuildStreamedSceneAssetBundle Detail:{0}", exp.Message);
                        successed = false;
                    }
                }
            }

            // 更新导出标志位
            if (successed == true)
            {
                BuildLogger.LogMessage(" -> BundlesConfig.UpdateBundleStateWhenCompleted");

                // 初始化检测信息(Hash Code)
                bundlesMap.UpdateUploadList(TBundleType.Scene);
                BuildLogger.LogMessage(" -> BundlesMap.UpdateUploadList Scene");
            }

            BuildInfo.GetInstance().ExportToJsonFile();
            BuildLogger.LogMessage(" -> BuildInfo.ExportToJsonFile");

            BuildLogger.CloseBlock();
        }
Esempio n. 13
0
        /// <summary>
        /// Default implementation of generating Asset Bundles using the Scriptable Build Pipeline.
        /// </summary>
        /// <param name="parameters">Set of parameters used for building asset bundles.</param>
        /// <param name="content">Set of content and explicit asset bundle layout to build.</param>
        /// <param name="result">Results from building the content and explicit asset bundle layout.</param>
        /// <param name="taskList">Custom task list for building asset bundles.</param>
        /// <param name="contextObjects">Additional context objects to make available to the build.</param>
        /// <returns>Return code with status information about success or failure causes.</returns>
        public static ReturnCode BuildAssetBundles(IBundleBuildParameters parameters, IBundleBuildContent content, out IBundleBuildResults result, IList <IBuildTask> taskList, params IContextObject[] contextObjects)
        {
            if (BuildPipeline.isBuildingPlayer)
            {
                result = null;
                BuildLogger.LogException(new InvalidOperationException("Cannot build asset bundles while a build is in progress"));
                return(ReturnCode.Exception);
            }

            // Avoid throwing exceptions in here as we don't want them bubbling up to calling user code
            if (parameters == null)
            {
                result = null;
                BuildLogger.LogException(new ArgumentNullException("parameters"));
                return(ReturnCode.Exception);
            }

            // Avoid throwing exceptions in here as we don't want them bubbling up to calling user code
            if (taskList.IsNullOrEmpty())
            {
                result = null;
                BuildLogger.LogException(new ArgumentException("Argument cannot be null or empty.", "taskList"));
                return(ReturnCode.Exception);
            }

            // Don't run if there are unsaved changes
            if (ValidationMethods.HasDirtyScenes())
            {
                result = null;
                return(ReturnCode.UnsavedChanges);
            }

            ThreadingManager.WaitForOutstandingTasks();
            BuildContext buildContext = new BuildContext(contextObjects);
            BuildLog     buildLog     = null;

            IBuildLogger logger;

            if (!buildContext.TryGetContextObject <IBuildLogger>(out logger))
            {
                logger = buildLog = new BuildLog();
                buildContext.SetContextObject(buildLog);
            }

            using (logger.ScopedStep(LogLevel.Info, "AssetDatabase.SaveAssets"))
                AssetDatabase.SaveAssets();

            ReturnCode exitCode;

            result = new BundleBuildResults();
            BuildCacheUtility.ClearCacheHashes();
            using (var interfacesWrapper = new BuildInterfacesWrapper())
#if !CI_TESTRUNNER_PROJECT
                using (new SceneStateCleanup())
                    using (var progressTracker = new ProgressTracker())
#else
                using (var progressTracker = new ProgressLoggingTracker())
#endif
                        using (var buildCache = new BuildCache(parameters.CacheServerHost, parameters.CacheServerPort))
                        {
                            Directory.CreateDirectory(parameters.TempOutputFolder);
                            Directory.CreateDirectory(parameters.ScriptOutputFolder);

                            try
                            {
                                buildContext.SetContextObject(parameters);
                                buildContext.SetContextObject(content);
                                buildContext.SetContextObject(result);
                                buildContext.SetContextObject(interfacesWrapper);
                                buildContext.SetContextObject(progressTracker);
                                buildContext.SetContextObject(buildCache);
                                // If IDeterministicIdentifiers was passed in with contextObjects, don't add the default
                                if (!buildContext.ContainsContextObject(typeof(IDeterministicIdentifiers)))
                                {
                                    buildContext.SetContextObject(parameters.ContiguousBundles ? new PrefabPackedIdentifiers() : (IDeterministicIdentifiers) new Unity5PackedIdentifiers());
                                }
                                buildContext.SetContextObject(new BuildDependencyData());
                                buildContext.SetContextObject(new BundleWriteData());
                                buildContext.SetContextObject(BuildCallbacks);
                                buildCache.SetBuildLogger(logger);
                            }
                            catch (Exception e)
                            {
                                // Avoid throwing exceptions in here as we don't want them bubbling up to calling user code
                                result = null;
                                BuildLogger.LogException(e);
                                return(ReturnCode.Exception);
                            }

                            exitCode = BuildTasksRunner.Validate(taskList, buildContext);
                            if (exitCode >= ReturnCode.Success)
#if SBP_PROFILER_ENABLE
                            { exitCode = BuildTasksRunner.RunProfiled(taskList, buildContext); }
#else
                            { exitCode = BuildTasksRunner.Run(taskList, buildContext); }
#endif

                            if (Directory.Exists(parameters.TempOutputFolder))
                            {
                                Directory.Delete(parameters.TempOutputFolder, true);
                            }

                            if (buildLog != null)
                            {
                                string buildLogPath = parameters.GetOutputFilePathForIdentifier("buildlogtep.json");
                                Directory.CreateDirectory(Path.GetDirectoryName(buildLogPath));
                                File.WriteAllText(parameters.GetOutputFilePathForIdentifier("buildlogtep.json"), buildLog.FormatForTraceEventProfiler());
                            }
                        }


            long maximumCacheSize = ScriptableBuildPipeline.maximumCacheSize * BuildCache.k_BytesToGigaBytes;
            BuildCache.PruneCache_Background(maximumCacheSize);
            return(exitCode);
        }
Esempio n. 14
0
        static void BuildForAndroid()
        {
            const string funcBlock = "ProjectBuild.BuildForAndroid()";

            BuildLogger.OpenBlock(funcBlock);

            // 设定打包信息
            SetBuildInfoFromParameters();

            TBuildMode buildMode = BuildInfo.GetInstance().BuildMode;

            BuildLogger.LogMessage("BuildMode:{0}", buildMode.ToString());

            // 输出格式({ProjectName}_v{ProjectVersion}_{buildNumber}_YYYYMMDDHHMMSS.apk)
            string buildTime = BuildParameters.BuildTime;

            // 输出路径
            // 游戏输出目录(Android):{OutputDir}/Android/{ProjectName}
            string outputDir = GetOutputDir(BuildTarget.Android, BuildParameters.OutputDir);

            if (outputDir == null)
            {
                BuildLogger.LogException("Create Dir Failed.!!(Dir:{0})",
                                         BuildParameters.OutputDir);
                throw new ApplicationException();
            }

            // 打包选项
            BuildOptions buildOptionTmp = BuildOptions.None;

            if (TBuildMode.Debug == buildMode)
            {
                buildOptionTmp |= BuildOptions.Development;
                buildOptionTmp |= BuildOptions.AllowDebugging;
                buildOptionTmp |= BuildOptions.ConnectWithProfiler;
            }
            else
            {
                bool isCheatMode = BuildParameters.IsCheatMode;
                if (true == isCheatMode)
                {
                    buildOptionTmp |= BuildOptions.Development;
                }
            }
            BuildLogger.LogMessage("BuildOption:{0}", ((int)buildOptionTmp).ToString());

            // 版本号
            string buildVersion = BuildInfo.GetInstance().BuildVersion;

            if (string.IsNullOrEmpty(buildVersion) == false)
            {
                PlayerSettings.bundleVersion = buildVersion;
            }
            BuildLogger.LogMessage("BuildVersion:{0}", buildVersion);

            // buildVersionCode
            int buildVersionCode = BuildInfo.GetInstance().BuildVersionCode;

            PlayerSettings.Android.bundleVersionCode = buildVersionCode;
            BuildLogger.LogMessage("BundleVersionCode:{0}", buildVersionCode.ToString());

            // 中心服务器版本号
            string centerVersion = BuildInfo.GetInstance().CenterVersion;

            BuildLogger.LogMessage("CenterVersion:{0}", centerVersion);

            // 工程名
            string projectName = BuildInfo.GetInstance().BuildName;

            BuildLogger.LogMessage("ProjectName:{0}", projectName);

            // 游戏名字
            string gameName = BuildParameters.GameName;

            if (true == string.IsNullOrEmpty(gameName))
            {
                gameName = projectName;
            }
            PlayerSettings.productName = gameName;
            BuildLogger.LogMessage("GameName:{0}", gameName);

            // BuildID
            string buildID = BuildInfo.GetInstance().BuildID;

            if (false == string.IsNullOrEmpty(buildID))
            {
#if UNITY_5_5_OR_NEWER
                PlayerSettings.applicationIdentifier = buildID;
#else
                PlayerSettings.bundleIdentifier = buildID;
#endif
            }
            BuildLogger.LogMessage("BuildID:{0}", buildID);

            // 初始化
            InitForAndroidBuild();
            BuildLogger.LogMessage(" --> InitForAndroidBuild()");

            // Apk输出路径
            int buildNumber = BuildInfo.GetInstance().BuildNumber;
            BuildLogger.LogMessage("BuildNumber:{0}", buildNumber.ToString());

            string apkPath = string.Format("{0}/{1}_{2}_v{3}_-_{4}_{5}.apk",
                                           outputDir,
                                           projectName,
                                           buildMode,
                                           buildVersion,
                                           buildTime, buildID);
            if (0 < buildNumber)
            {
                apkPath = string.Format("{0}/{1}_{2}_v{3}_{4}_{5}_{6}.apk",
                                        outputDir,
                                        projectName,
                                        buildMode,
                                        buildVersion,
                                        buildNumber,
                                        buildTime, buildID);
            }
            BuildLogger.LogMessage("Apk File Path:{0}", apkPath);

            // 输出打包信息
            OutputBuildInfo(buildVersion, projectName);

            // 开发者模式
            if (BuildOptions.Development == buildOptionTmp)
            {
                // 打包之前,移除非资源对象
                AssetBundles.Common.MoveUnResources();
            }

            // Android下IL2CPP不支持,所以设置回Mono
            PlayerSettings.SetPropertyInt("ScriptingBackend", (int)ScriptingImplementation.Mono2x, BuildTarget.Android);

            string error = BuildPipeline.BuildPlayer(GetBuildScenes(), apkPath, BuildTarget.Android, buildOptionTmp);

            // 开发者模式
            if (BuildOptions.Development == buildOptionTmp)
            {
                // 打包之后,恢复非资源对象
                AssetBundles.Common.MoveBackUnResources();
            }

            if (error != null && !error.Equals("") && !(error.Length == 0))
            {
                BuildLogger.LogException("Android Build Failed!!!(error:{0})", error);
                BuildLogger.CloseBlock();
                throw new ApplicationException();
            }
            else
            {
                BuildLogger.LogMessage("Android Build Successed.");
            }
            BuildLogger.CloseBlock();
        }
Esempio n. 15
0
        static void ExportXcodeProject()
        {
            const string funcBlock = "ProjectBuild.ExportXcodeProject()";

            BuildLogger.OpenBlock(funcBlock);

            // 设定打包信息
            SetBuildInfoFromParameters();
            // 平台类型
            BuildInfo.GetInstance().PlatformType = TPlatformType.iOS;

            TBuildMode buildMode = BuildInfo.GetInstance().BuildMode;

            BuildLogger.LogMessage("BuildMode:{0}", buildMode.ToString());

            // 初始化
            InitForExportXcodeProject();
            BuildLogger.LogMessage(" --> InitForExportXcodeProject()");

            // 预定义宏
            //PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.iOS, "GAMELINK");

            // 游戏输出目录(iOS):{OutputDir}/iOS/{ProjectName}
            string outputDir = GetOutputDir(BuildTarget.iOS, null);

            if (outputDir == null)
            {
                BuildLogger.LogException("Create Dir Failed.!!(Dir:{0})",
                                         BuildParameters.OutputDir);
                throw new ApplicationException();
            }

            // 打包选项
            BuildOptions buildOptionTmp = BuildOptions.None;

            if (TBuildMode.Debug == buildMode)
            {
                buildOptionTmp |= BuildOptions.Development;
                buildOptionTmp |= BuildOptions.AllowDebugging;
                buildOptionTmp |= BuildOptions.ConnectWithProfiler;
            }
            else
            {
                bool isCheatMode = BuildParameters.IsCheatMode;
                if (true == isCheatMode)
                {
                    buildOptionTmp |= BuildOptions.Development;
                }
            }
            BuildLogger.LogMessage("BuildOption:{0}", ((int)buildOptionTmp).ToString());

            // 工程名
            string projectName = BuildInfo.GetInstance().BuildName;

            BuildLogger.LogMessage("ProjectName:{0}", projectName);

            // 游戏名字
            string gameName = BuildParameters.GameName;

            if (true == string.IsNullOrEmpty(gameName))
            {
                gameName = projectName;
            }
            PlayerSettings.iOS.applicationDisplayName = gameName;
            BuildLogger.LogMessage("GameName:{0}", gameName);

            // BuildID
            string buildID = BuildInfo.GetInstance().BuildID;

            if (false == string.IsNullOrEmpty(buildID))
            {
#if UNITY_5_5_OR_NEWER
                PlayerSettings.applicationIdentifier = buildID;
#else
                PlayerSettings.bundleIdentifier = buildID;
#endif
            }
            BuildLogger.LogMessage("BuildID:{0}", buildID);

            // 版本号
            string buildVersion = BuildInfo.GetInstance().BuildVersion;
            PlayerSettings.bundleVersion = buildVersion;
            BuildLogger.LogMessage("BuildVersion:{0}", buildVersion);

            // 中心服务器版本号
            string centerVersion = BuildInfo.GetInstance().CenterVersion;
            BuildLogger.LogMessage("CenterVersion:{0}", centerVersion);

            // XCode工程目录
            string XcodeProject = string.Format("{0}/XcodeProject", outputDir);

            // 输出打包信息
            OutputBuildInfo(buildVersion, projectName);

            // 开发者模式
            if (BuildOptions.Development == buildOptionTmp)
            {
                // 打包之前,将非资源对象,临时移动到临时文件夹
                AssetBundles.Common.MoveUnResources();
            }

            // 打包成XCode工程目录
                        #if UNITY_5_OR_NEWER
            string error = BuildPipeline.BuildPlayer(
                GetBuildScenes(),
                XcodeProject,
                BuildTarget.iOS, buildOptionTmp);
                        #else
            string error = BuildPipeline.BuildPlayer(
                GetBuildScenes(),
                XcodeProject,
                BuildTarget.iOS, buildOptionTmp);
                        #endif

            // 开发者模式
            if (BuildOptions.Development == buildOptionTmp)
            {
                // 恢复非资源性文件
                AssetBundles.Common.MoveBackUnResources();
            }

            // 存在错误则,打包编译失败
            if (error != null && !error.Equals("") && !(error.Length == 0))
            {
                BuildLogger.LogException("iOS Build Failed!!!(error:{0})", error);
                BuildLogger.CloseBlock();
                throw new ApplicationException();
            }
            else
            {
                BuildLogger.LogMessage("iOS Build Successed.");
            }
            BuildLogger.CloseBlock();
        }