Example #1
0
        internal static ICodeBlock GenerateInitialize(IElement saveObject)
        {

            ICodeBlock codeBlock = new CodeDocument(3);
            ICodeBlock currentBlock = codeBlock;

            // Start measuring performance before anything else
            PerformancePluginCodeGenerator.GenerateStartTimingInitialize(saveObject, codeBlock);

            PerformancePluginCodeGenerator.SaveObject = saveObject;
            PerformancePluginCodeGenerator.CodeBlock = codeBlock;

            PerformancePluginCodeGenerator.GenerateStart("CustomLoadStaticContent from Initialize");

            // Load static content before looping through the CodeGenerators
            // The reason for this is there is a ReferencedFileSaveCodeGenerator
            // which needs to work with static RFS's which are instantiated here
            currentBlock.Line("LoadStaticContent(ContentManagerName);");

            PerformancePluginCodeGenerator.GenerateEnd();


            PerformancePluginCodeGenerator.GenerateStart("General Initialize internals");

            foreach (ElementComponentCodeGenerator codeGenerator in CodeGenerators)
            {
                codeGenerator.GenerateInitialize(codeBlock, saveObject);
            }




            foreach (ElementComponentCodeGenerator codeGenerator in CodeGenerators)
            {
                codeGenerator.GenerateInitializeLate(codeBlock, saveObject);
            }

            if (saveObject is ScreenSave)
            {
                ScreenSave asScreenSave = saveObject as ScreenSave;
                codeBlock._();

                if (asScreenSave.IsRequiredAtStartup)
                {
                    string startupScreen = ProjectManager.StartUpScreen;

                    string qualifiedName = ProjectManager.ProjectNamespace + "." + startupScreen.Replace("\\", ".");

                    codeBlock.Line(string.Format("this.NextScreen = typeof({0}).FullName;", qualifiedName));
                }

                if (asScreenSave.UseGlobalContent)
                {
                    // no need to do anything here because Screens are smart enough to know to not load if they
                    // are using global content
                }

                if (!string.IsNullOrEmpty(asScreenSave.NextScreen))
                {
                    string nameToUse = ProjectManager.ProjectNamespace + "." + asScreenSave.NextScreen.Replace("\\", ".");

                    codeBlock.Line(string.Format("this.NextScreen = typeof({0}).FullName;", nameToUse));
                }

            }











            codeBlock._();
            PerformancePluginCodeGenerator.GenerateEnd();

            #region PostInitializeCode

            PerformancePluginCodeGenerator.GenerateStart("Post Initialize");


            if (saveObject.InheritsFromElement() == false)
            {
                codeBlock.Line("PostInitialize();");
            }
            PerformancePluginCodeGenerator.GenerateEnd();

            #endregion

            PerformancePluginCodeGenerator.GenerateStart("Base.Initialize");


            InheritanceCodeWriter.Self.WriteBaseInitialize(saveObject, codeBlock);

            PerformancePluginCodeGenerator.GenerateEnd();

            // I think we want to set this after calling base.Initialize so that the base
            // has a chance to set values on derived objects
            PerformancePluginCodeGenerator.GenerateStart("Reset Variables");
            // Now that variables are set, we can record reset variables
            NamedObjectSaveCodeGenerator.AssignResetVariables(codeBlock, saveObject);
            PerformancePluginCodeGenerator.GenerateEnd();

            PerformancePluginCodeGenerator.GenerateStart("AddToManagers");


            #region If shouldCallAddToManagers, call AddToManagers
            bool shouldCallAddToManagers = !saveObject.InheritsFromElement();
            if (shouldCallAddToManagers)
            {
                currentBlock = currentBlock
                    .If("addToManagers");
                if (saveObject is ScreenSave)
                {
                    currentBlock.Line("AddToManagers();");
                }
                else
                {
                    currentBlock.Line("AddToManagers(null);");
                }
            }

            #endregion
            PerformancePluginCodeGenerator.GenerateEnd();

            PerformancePluginCodeGenerator.GenerateEndTimingInitialize(saveObject, codeBlock);

            return codeBlock;
        }
Example #2
0
        public static ICodeBlock CreateClass(string namespaceName, string className, bool isPartial, List<TypedMemberBase> members,
            bool isStatic, List<string> usingStatements, Dictionary<string, string> untypedMembers, ICodeBlock methodContent)
        {
            var codeBlock = new CodeDocument();

            #region Append Using Statements
            foreach(var usingStatement in usingStatements.Distinct())
            {
                codeBlock.Line("using " + usingStatement + ";");
            }
            #endregion

            #region Append Namespace

            codeBlock._();

            ICodeBlock currentBlock = codeBlock;

            currentBlock = currentBlock.Namespace(namespaceName);

            #endregion

            #region Append class header

            currentBlock = currentBlock.Class(className, Public: true, Static: isStatic, Partial: isPartial);

            #endregion

            for (int i = 0; i < members.Count; i++)
            {
                TypedMemberBase member = members[i];


                bool isPublic = member.Modifier == Modifier.Public;
                bool isPrivate = member.Modifier == Modifier.Private;
                bool isInternal = member.Modifier == Modifier.Internal;

                string memberType = member.MemberType.ToString();

                memberType = PrepareTypeToBeWritten(member, memberType);

                // We used to remove whitespace here,
                // but the member name may contain an assignment.
                // In that case we want spaces preserved.  Whatever
                // calls this method is in charge of removing whitespace.
                string memberName = member.MemberName;

                currentBlock.Line(StringHelper.Modifiers(
                    Public: isPublic, 
                    Private: isPrivate,
                    Internal: isInternal,
                    Static: isStatic, 
                    Type: memberType, 
                    Name: memberName) + ";");
            }

            foreach (KeyValuePair<string, string> kvp in untypedMembers)
            {
                string memberName = kvp.Key;
                string type = kvp.Value;


                bool isPublic = !memberName.StartsWith("m");

                currentBlock.Line(StringHelper.Modifiers(Public: isPublic, Static: isStatic, Type: type, Name: memberName) + ";");
            }


            if (methodContent == null)
            {
                currentBlock.Tag("Methods");
            }
            else
            {
                currentBlock.InsertBlock(methodContent);
            }

            currentBlock._()._();

            currentBlock.Replace(" System.Single ", " float ");
            currentBlock.Replace(" System.Boolean ", " bool ");
            currentBlock.Replace(" System.Int32 ", " int ");
            currentBlock.Replace(" System.String ", " string ");

            return codeBlock;
        }
        private static ICodeBlock GetGlobalContentFilesMethods()
        {
            ICodeBlock codeBlock = new CodeDocument();
            var currentBlock = codeBlock;

            codeBlock._();

            // Don't use foreach to make this tolerate changes to the collection while it generates
            //foreach (ReferencedFileSave rfs in ProjectManager.GlueProjectSave.GlobalFiles)
            for (int i = 0; i < ProjectManager.GlueProjectSave.GlobalFiles.Count; i++ )
            { 
                ReferencedFileSave rfs  = ProjectManager.GlueProjectSave.GlobalFiles[i];

                ReferencedFileSaveCodeGenerator.AppendFieldOrPropertyForReferencedFile(currentBlock, rfs, GlobalContentContainerName, null);
            }

            const bool inheritsFromElement = false;
            ReferencedFileSaveCodeGenerator.GenerateGetStaticMemberMethod(ProjectManager.GlueProjectSave.GlobalFiles, currentBlock, true, inheritsFromElement);
            ReferencedFileSaveCodeGenerator.GenerateGetFileMethodByName(
                ProjectManager.GlueProjectSave.GlobalFiles, currentBlock, false, "GetFile", false);
            if (ProjectManager.GlueProjectSave.GlobalContentSettingsSave.RecordLockContention)
            {
                currentBlock.Line("public static List<string> LockRecord = new List<string>();");
            }

            currentBlock
                .AutoProperty("public static bool", "IsInitialized", "", "private");

            currentBlock
                .AutoProperty("public static bool", "ShouldStopLoading");

            currentBlock.Line("const string ContentManagerName = \"Global\";");

            currentBlock = currentBlock
                .Function("public static void", "Initialize", "")
                    ._();

            //stringBuilder.AppendLine("\t\t\tstring ContentManagerName = \"Global\";");

            // Do the high-proprity loads first
            // Update May 10, 2011
            // If loading asynchronously
            // the first Screen may load before
            // we even get to the high-priority RFS's
            // (which are localization).  This could cause
            // the first Screen to have unlocalized text.  That's
            // why we want to load it before we even start our async loading.
            foreach (ReferencedFileSave rfs in ProjectManager.GlueProjectSave.GlobalFiles)
            {
                if (IsRfsHighPriority(rfs))
                {
                    ReferencedFileSaveCodeGenerator.GetInitializationForReferencedFile(rfs, null, currentBlock, true, LoadType.CompleteLoad);
                }
            }

            bool loadAsync = ProjectManager.GlueProjectSave.GlobalContentSettingsSave.LoadAsynchronously;

            if (loadAsync)
            {

                currentBlock.Line("#if !REQUIRES_PRIMARY_THREAD_LOADING");
                    currentBlock.Line("NamedDelegate namedDelegate = new NamedDelegate();");

                    foreach (ReferencedFileSave rfs in ProjectManager.GlueProjectSave.GlobalFiles)
                    {
                        if (!IsRfsHighPriority(rfs) && !rfs.LoadedOnlyWhenReferenced && rfs.LoadedAtRuntime)
                        {
                            currentBlock.Line("namedDelegate.Name = \"" + rfs.Name + "\";");
                            currentBlock.Line("namedDelegate.LoadMethod = Load" + rfs.Name.Replace("/", "_").Replace(".", "_") + ";");
                            currentBlock.Line("LoadMethodList.Add( namedDelegate );");
                        }
                    }

                    currentBlock._();

                    currentBlock.Line("#if WINDOWS_8");
                        currentBlock.Line("System.Threading.Tasks.Task.Run((System.Action)AsyncInitialize);");
                    currentBlock.Line("#else");

                        currentBlock.Line("ThreadStart threadStart = new ThreadStart(AsyncInitialize);");
                        currentBlock.Line("Thread thread = new Thread(threadStart);");
                        currentBlock.Line("thread.Name = \"GlobalContent Async load\";");
                        currentBlock.Line("thread.Start();");
                    currentBlock.Line("#endif");
                currentBlock.Line("#endif");

                currentBlock = currentBlock.End();

                currentBlock._();


                currentBlock.Line("#if !REQUIRES_PRIMARY_THREAD_LOADING");

                currentBlock
                    .Function("static void", "RequestContentLoad", "string contentName")
                        .Lock("LoadMethodList")
                            .Line("int index = -1;")
                            .For("int i = 0; i < LoadMethodList.Count; i++")
                                .If("LoadMethodList[i].Name == contentName")
                                    .Line("index = i;")
                                    .Line("break;")
                                .End()
                            .End()
                            .If("index != -1")
                                .Line("NamedDelegate delegateToShuffle = LoadMethodList[index];")
                                .Line("LoadMethodList.RemoveAt(index);")
                                .Line("LoadMethodList.Insert(0, delegateToShuffle);")
                            .End()
                        .End()
                    .End();
                currentBlock.Line("#endif");

                currentBlock._();

                currentBlock.Line("#if !REQUIRES_PRIMARY_THREAD_LOADING");
                currentBlock
                    .Function("static void", "AsyncInitialize", "")

                        .Line("#if XBOX360")
                        .Line("// We can not use threads 0 or 2")
                        .Line("// Async screen loading uses thread 4, so we'll use 3 here")
                        .Line("Thread.CurrentThread.SetProcessorAffinity(3);")
                        .Line("#endif")

                        .Line("bool shouldLoop = LoadMethodList.Count != 0;")

                        .While("shouldLoop")
                            .Line("System.Action action = null;")
                            .Lock("LoadMethodList")

                                .Line("action = LoadMethodList[0].LoadMethod;")
                                .Line("LoadMethodList.RemoveAt(0);")
                                .Line("shouldLoop = LoadMethodList.Count != 0 && !ShouldStopLoading;")

                            .End()
                            .Line("action();")
                        .End()
                        .Line("IsInitialized = true;")
                        ._()
                    .End();
                currentBlock.Line("#endif");

                //stringBuilder.AppendLine("\t\t\tstring ContentManagerName = \"Global\";");

            }

            if (ContentLoadWriter.SuppressGlobalContentDictionaryRefresh == false)
            {
                ReferencedFileSaveCodeGenerator.RefreshGlobalContentDictionary();
            }

            if (loadAsync)
            {
                currentBlock.Line("#if !REQUIRES_PRIMARY_THREAD_LOADING");
            }

            foreach (ReferencedFileSave rfs in ProjectManager.GlueProjectSave.GlobalFiles)
            {
                if (!IsRfsHighPriority(rfs) && rfs.LoadedAtRuntime)
                {

                    if (loadAsync)
                    {
                        currentBlock = currentBlock
                            .Function("static void", "Load" + rfs.Name.Replace("/", "_").Replace(".", "_"), "");
                    }


                    ReferencedFileSaveCodeGenerator.GetInitializationForReferencedFile(rfs, null, currentBlock, true, LoadType.CompleteLoad);

                    if (loadAsync)
                    {
                        currentBlock.Line("m" + rfs.GetInstanceName() + "Mre.Set();");
                        currentBlock = currentBlock.End();
                    }

                }
            }

            if (loadAsync)
            {
                currentBlock.Line("#endif");
            }

            if (!loadAsync)
            {
                currentBlock = currentBlock
                        .Line("\t\t\tIsInitialized = true;")
                    .End();
            }


            GenerateReloadFileMethod(currentBlock);

            return codeBlock;
        }
        private static ICodeBlock GetGlobalContentFilesMethods()
        {
            ICodeBlock codeBlock = new CodeDocument();
            var currentBlock = codeBlock;
            var classLevelBlock = currentBlock;

            codeBlock._();

            // Don't use foreach to make this tolerate changes to the collection while it generates
            //foreach (ReferencedFileSave rfs in ProjectManager.GlueProjectSave.GlobalFiles)
            for (int i = 0; i < ProjectManager.GlueProjectSave.GlobalFiles.Count; i++)
            {
                ReferencedFileSave rfs = ProjectManager.GlueProjectSave.GlobalFiles[i];

                ReferencedFileSaveCodeGenerator.AppendFieldOrPropertyForReferencedFile(currentBlock, rfs, GlobalContentContainerName, null);
            }

            const bool inheritsFromElement = false;
            ReferencedFileSaveCodeGenerator.GenerateGetStaticMemberMethod(ProjectManager.GlueProjectSave.GlobalFiles, currentBlock, true, inheritsFromElement);
            ReferencedFileSaveCodeGenerator.GenerateGetFileMethodByName(
                ProjectManager.GlueProjectSave.GlobalFiles, currentBlock, false, "GetFile", false);
            if (ProjectManager.GlueProjectSave.GlobalContentSettingsSave.RecordLockContention)
            {
                currentBlock.Line("public static List<string> LockRecord = new List<string>();");
            }

            currentBlock
                .AutoProperty("public static bool", "IsInitialized", "", "private");

            currentBlock
                .AutoProperty("public static bool", "ShouldStopLoading");

            currentBlock.Line("const string ContentManagerName = \"Global\";");

            var initializeFunction =
                currentBlock.Function("public static void", "Initialize", "");

            currentBlock = initializeFunction
                    ._();

            

            //stringBuilder.AppendLine("\t\t\tstring ContentManagerName = \"Global\";");

            // Do the high-proprity loads first
            // Update May 10, 2011
            // If loading asynchronously
            // the first Screen may load before
            // we even get to the high-priority RFS's
            // (which are localization).  This could cause
            // the first Screen to have unlocalized text.  That's
            // why we want to load it before we even start our async loading.
            foreach (ReferencedFileSave rfs in ProjectManager.GlueProjectSave.GlobalFiles)
            {
                if (IsRfsHighPriority(rfs))
                {
                    ReferencedFileSaveCodeGenerator.GetInitializationForReferencedFile(rfs, null, initializeFunction, true, LoadType.CompleteLoad);
                }
            }

            bool loadAsync = GenerateLoadAsyncCode(classLevelBlock, initializeFunction);

            if (ContentLoadWriter.SuppressGlobalContentDictionaryRefresh == false)
            {
                ReferencedFileSaveCodeGenerator.RefreshGlobalContentDictionary();
            }

            if (loadAsync)
            {
                currentBlock.Line("#if !REQUIRES_PRIMARY_THREAD_LOADING");
            }

            foreach (ReferencedFileSave rfs in ProjectManager.GlueProjectSave.GlobalFiles)
            {
                if (!IsRfsHighPriority(rfs) && rfs.LoadedAtRuntime)
                {
                    var blockToUse = initializeFunction;

                    if (loadAsync)
                    {
                        blockToUse = classLevelBlock
                            .Function("static void", "Load" + rfs.Name.Replace("/", "_").Replace(".", "_"), "");
                    }


                    ReferencedFileSaveCodeGenerator.GetInitializationForReferencedFile(rfs, null, blockToUse, true, LoadType.CompleteLoad);

                    if (loadAsync)
                    {
                        blockToUse.Line("m" + rfs.GetInstanceName() + "Mre.Set();");
                        blockToUse.End();
                    }

                }
            }

            if (loadAsync)
            {
                currentBlock.Line("#endif");
            }

            if (!loadAsync)
            {
                currentBlock = currentBlock
                        .Line("\t\t\tIsInitialized = true;")
                    .End();
            }


            GenerateReloadFileMethod(classLevelBlock);

            

            foreach (var generator in CodeWriter.GlobalContentCodeGenerators)
            {
                generator.GenerateInitializeEnd(initializeFunction);
                generator.GenerateAdditionalMethods(classLevelBlock);
            }

            return codeBlock;
        }
        private static ICodeBlock GetAllFactoryMethods(string factoryClassName, string baseClassName, int numberToPreAllocate, bool poolObjects)
        {
            string className = factoryClassName.Substring(0, factoryClassName.Length - "Factory".Length);

            ICodeBlock codeBlock = new CodeDocument();

            GetCreateNewFactoryMethod(codeBlock, factoryClassName, poolObjects, baseClassName);
            codeBlock._();
            GetInitializeFactoryMethod(codeBlock, className, poolObjects, "mScreenListReference");
            codeBlock._();

            if (!string.IsNullOrEmpty(baseClassName))
            {
                GetInitializeFactoryMethod(codeBlock, FileManager.RemovePath(baseClassName), poolObjects, "mBaseScreenListReference");
                codeBlock._();
            }

            GetDestroyFactoryMethod(codeBlock, factoryClassName);
            codeBlock._();
            GetFactoryInitializeMethod(codeBlock, factoryClassName, numberToPreAllocate);
            codeBlock._();
            GetMakeUnusedFactory(codeBlock, factoryClassName, poolObjects);

            return codeBlock;
        }