private static void GenerateList(ICodeBlock codeBlock, NamedObjectSave namedObject)
        {
            codeBlock = codeBlock.Block();
            {
                codeBlock.Line($"var listId = {GetAddToContainerStringFor(namedObject)};");

                var instanceName = namedObject.InstanceName;
                codeBlock.Line($"this.{instanceName}.CollectionChanged += (sender, args) =>");
                var block1 = codeBlock.Block();
                {
                    var block2 = block1.If("args.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add");
                    {
                        var foreachBlock = block2.ForEach("var item in args.NewItems");
                        {
                            foreachBlock.Line($"containerManager.AddObjectToContainer(\"CurrentScreen\", item, \"{instanceName}.\" + item.GetType().Name + \"Instance\", listId);");
                        }
                    }
                    block2 = block1.ElseIf("args.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove");
                    {
                        var foreachBlock = block2.ForEach("var item in args.OldItems");
                        {
                            foreachBlock.Line("containerManager.RemoveInstanceByObject(item);");
                        }
                    }
                };
                codeBlock.Line(";");
            }
        }
Exemplo n.º 2
0
        private static ICodeBlock GeneratePreloadStateContentForStateType(ICodeBlock codeBlock, IElement element, List <StateSave> list, string variableType)
        {
            if (list.Count != 0)
            {
                codeBlock = codeBlock.Function("public static void", "PreloadStateContent", variableType + " state, string contentManagerName");
                codeBlock.Line("ContentManagerName = contentManagerName;");

                codeBlock = codeBlock.Switch("state");

                // Loop through states here and access properties that need the values
                foreach (StateSave state in list)
                {
                    codeBlock = codeBlock.Case(variableType + "." + state.Name);
                    foreach (InstructionSave instruction in state.InstructionSaves)
                    {
                        if (instruction.Value != null && instruction.Value is string)
                        {
                            // We insert a block so that object throwaway is not redefined in the switch scope.
                            // We do this instead of making an object throwaway above the switch so that we don't
                            // get warnings if is nothing to load
                            codeBlock.Block().Line("object throwaway = " + GetRightSideAssignmentValueAsString(element, instruction) + ";");
                        }
                    }
                    codeBlock = codeBlock.End();
                }

                codeBlock = codeBlock.End();

                codeBlock = codeBlock.End();
            }
            return(codeBlock);
        }
Exemplo n.º 3
0
        private static void GenerateStaticCameraSetupData(ICodeBlock classContents)
        {
            classContents.Line("public static CameraSetupData Data = new CameraSetupData");
            var block = classContents.Block();

            var displaySettings = GlueState.Self.CurrentGlueProject.DisplaySettings;

            block.Line($"Scale = {(displaySettings.Scale ).ToString(CultureInfo.InvariantCulture)}f,");
            block.Line($"ResolutionWidth = {displaySettings.ResolutionWidth},");
            block.Line($"ResolutionHeight = {displaySettings.ResolutionHeight},");
            block.Line($"Is2D = {displaySettings.Is2D.ToString().ToLowerInvariant()},");

            if (displaySettings.FixedAspectRatio)
            {
                decimal aspectRatioValue = 1;

                if (displaySettings.AspectRatioHeight != 0)
                {
                    aspectRatioValue = displaySettings.AspectRatioWidth / displaySettings.AspectRatioHeight;
                }
                block.Line($"AspectRatio = {aspectRatioValue.ToString(CultureInfo.InvariantCulture).ToLowerInvariant()}m,");
            }

            block.Line($"IsFullScreen = {displaySettings.RunInFullScreen.ToString().ToLowerInvariant()},");
            block.Line($"AllowWidowResizing = {displaySettings.AllowWindowResizing.ToString().ToLowerInvariant()},");
            block.Line($"ResizeBehavior = ResizeBehavior.{displaySettings.ResizeBehavior},");

            if (GetIfHasGumProject())
            {
                block.Line($"ResizeBehaviorGum = ResizeBehavior.{displaySettings.ResizeBehaviorGum},");
            }

            block.Line($"DominantInternalCoordinates = WidthOrHeight.{displaySettings.DominantInternalCoordinates},");
            classContents.Line(";");
        }
Exemplo n.º 4
0
        private void CreateInstructionForInterpolation(StateCodeGeneratorContext context, ICodeBlock currentBlock, string animationType, AnimatedStateSave previousState, AnimatedStateSave currentState, AbsoluteOrRelative absoluteOrRelative, string animationName)
        {
            currentBlock = currentBlock.Block();

            if (absoluteOrRelative == AbsoluteOrRelative.Absolute)
            {
                CreateInstructionForInterpolationAbsolute(context, currentBlock, animationType, previousState, currentState, animationName);
            }
            else
            {
                CreateInstructionForInterpolationRelative(context, currentBlock, previousState, currentState);
            }
            currentBlock = currentBlock.End();
        }
        public static void HandleWriteInstanceVariableAssignment(NamedObjectSave instance, ICodeBlock code, InstructionSave variable)
        {
            var shouldHandle = variable.Member == "AtlasedTexture" && instance.SourceClassType == "Sprite";

            if (shouldHandle)
            {
                var memberName = instance.InstanceName;

                // The code should look something like:
                //
                // SpriteInstance.AtlasedTexture = FlatRedBall.Graphics.Texture.AtlasLoader.LoadAtlasedTexture("asdf");
                //
                // But I still need to make the AtlasLoader keep track of all loaded assets, and I need to have a "priority" system

                code = code.Block();
                {
                    // eventually this might exist
                    //var atlas = instance.GetInstructionFromMember("");
                    // for now we assume that the texture packer project is in global content
                    var rfs = GlueState.Self.CurrentGlueProject.GlobalFiles.FirstOrDefault(item =>
                    {
                        var ati = item.GetAssetTypeInfo();
                        if (ati != null)
                        {
                            return(ati == AtiManager.Self.TextureAtlasAti);
                        }

                        return(false);
                    });

                    if (rfs != null)
                    {
                        var atlas = $"{GlueState.Self.ProjectNamespace}.GlobalContent.{rfs.GetInstanceName()}";
                        code.Line($"var atlas = {atlas};");

                        code.Line($"{memberName}.AtlasedTexture = atlas.Sprite(\"{variable.Value}\");");
                    }
                }
            }
        }
        public static void HandleWriteInstanceVariableAssignment(NamedObjectSave instance, ICodeBlock code, InstructionSave variable)
        {
            var shouldHandle = variable.Member == "AtlasedTexture" && instance.SourceClassType == "Sprite";

            if(shouldHandle)
            {
                var memberName = instance.InstanceName;

                // The code should look something like:
                // 
                // SpriteInstance.AtlasedTexture = FlatRedBall.Graphics.Texture.AtlasLoader.LoadAtlasedTexture("asdf");
                //
                // But I still need to make the AtlasLoader keep track of all loaded assets, and I need to have a "priority" system

                code = code.Block();
                {
                    // eventually this might exist
                    //var atlas = instance.GetInstructionFromMember("");
                    // for now we assume that the texture packer project is in global content
                    var rfs = GlueState.Self.CurrentGlueProject.GlobalFiles.FirstOrDefault(item =>
                    {
                        var ati = item.GetAssetTypeInfo();
                        if(ati != null)
                        {
                            return ati == AtiManager.Self.TextureAtlasAti;
                        }

                        return false;
                    });

                    if (rfs != null)
                    {
                        var atlas = $"{GlueState.Self.ProjectNamespace}.GlobalContent.{rfs.GetInstanceName()}";
                        code.Line($"var atlas = {atlas};");

                        code.Line($"{memberName}.AtlasedTexture = atlas.Sprite(\"{variable.Value}\");");
                    }
                }
            }
        }
Exemplo n.º 7
0
        private static void CreateInstructionForSubAnimation(ICodeBlock currentBlock, AnimationReferenceSave animationReferenceSave, AbsoluteOrRelative absoluteOrRelative, AnimationSave parentAnimation, StateCodeGeneratorContext context)
        {
            currentBlock = currentBlock.Block();

            //var instruction = new FlatRedBall.Instructions.DelegateInstruction(() =>
            //FlatRedBall.Instructions.InstructionManager.Instructions.AddRange(ClickableBushInstance.GrowAnimation));
            //instruction.TimeToExecute = FlatRedBall.TimeManager.CurrentTime + asdf;
            //yield return instruction;

            var isReferencingMissingInstance = !string.IsNullOrEmpty(animationReferenceSave.SourceObject) &&
                                               context.Element.GetInstance(animationReferenceSave.SourceObject) == null;

            ////////////////Early Out///////////////
            if (isReferencingMissingInstance)
            {
                currentBlock.Line($"// This animation references a missing instance named {animationReferenceSave.SourceObject}");
                return;
            }
            /////////////End Early Out/////////////


            string animationName = animationReferenceSave.PropertyNameInCode();

            //animationReferenceSave. FlatRedBall.IO.FileManager.RemovePath(animationReferenceSave.Name) + "Animation";
            if (absoluteOrRelative == AbsoluteOrRelative.Relative)
            {
                animationName += "Relative";
            }

            currentBlock.Line($"var instruction = new FlatRedBall.Instructions.DelegateInstruction(()=>{animationName}.Play({parentAnimation.PropertyNameInCode()}));");
            currentBlock.Line("instruction.TimeToExecute = FlatRedBall.TimeManager.CurrentTime + " + ToFloatString(animationReferenceSave.Time) + ";");


            currentBlock.Line("yield return instruction;");
            currentBlock = currentBlock.End();
        }
        private static void CreateInstructionForSubAnimation(ICodeBlock currentBlock, AnimationReferenceSave animationReferenceSave, AbsoluteOrRelative absoluteOrRelative, AnimationSave parentAnimation)
        {
            currentBlock = currentBlock.Block();

            //var instruction = new FlatRedBall.Instructions.DelegateInstruction(() =>
            //FlatRedBall.Instructions.InstructionManager.Instructions.AddRange(ClickableBushInstance.GrowAnimation));
            //instruction.TimeToExecute = FlatRedBall.TimeManager.CurrentTime + asdf;
            //yield return instruction;

            string animationName = animationReferenceSave.PropertyNameInCode();

            //animationReferenceSave. FlatRedBall.IO.FileManager.RemovePath(animationReferenceSave.Name) + "Animation";
            if (absoluteOrRelative == AbsoluteOrRelative.Relative)
            {
                animationName += "Relative";
            }

            currentBlock.Line($"var instruction = new FlatRedBall.Instructions.DelegateInstruction(()=>{animationName}.Play({parentAnimation.PropertyNameInCode()}));");
            currentBlock.Line("instruction.TimeToExecute = FlatRedBall.TimeManager.CurrentTime + " + ToFloatString(animationReferenceSave.Time) + ";");


            currentBlock.Line("yield return instruction;");
            currentBlock = currentBlock.End();
        }
Exemplo n.º 9
0
        private void GenerateGetEnumerableFor(StateCodeGeneratorContext context, ICodeBlock currentBlock, AnimationSave animation, AbsoluteOrRelative absoluteOrRelative)
        {
            string animationType = "VariableState";

            string animationName = animation.PropertyNameInCode();

            if (absoluteOrRelative == AbsoluteOrRelative.Relative)
            {
                animationName += "Relative";
            }

            string propertyName = animationName + "Instructions";

            // Instructions used to be public - the user would grab them and add them to the InstructionManager,
            // but now everything is encased in an Animation object which handles stopping itself and provides a simple
            // Play method.

            const string signature = "private System.Collections.Generic.IEnumerable<FlatRedBall.Instructions.Instruction>";

            if (animation.States.Count == 0 && animation.Animations.Count == 0)
            {
                currentBlock = currentBlock.Function(signature, propertyName, "object target");

                currentBlock.Line("yield break;");
            }
            else if (absoluteOrRelative == AbsoluteOrRelative.Relative && animation.States.Count < 2 && animation.Animations.Count == 0)
            {
                currentBlock = currentBlock.Function(signature, propertyName, "object target");

                currentBlock.Line("yield break;");
            }
            else
            {
                if (animation.States.Count != 0)
                {
                    var firstState = context.Element.AllStates.FirstOrDefault(item => item.Name == animation.States.First().StateName);

                    var category = context.Element.Categories.FirstOrDefault(item => item.States.Contains(firstState));

                    if (category != null)
                    {
                        animationType = category.Name;
                    }
                }

                currentBlock = currentBlock.Function(signature, propertyName, "object target");

                GenerateOrderedStateAndSubAnimationCode(context, currentBlock, animation, animationType, absoluteOrRelative);

                if (animation.Loops)
                {
                    currentBlock = currentBlock.Block();

                    currentBlock.Line("var toReturn = new FlatRedBall.Instructions.DelegateInstruction(  " +
                                      "() => FlatRedBall.Instructions.InstructionManager.Instructions.AddRange(this." + propertyName + "(target)));");
                    string executionTime = "0.0f";

                    if (animation.States.Count != 0)
                    {
                        executionTime = ToFloatString(animation.States.Last().Time);
                    }

                    currentBlock.Line("toReturn.TimeToExecute = FlatRedBall.TimeManager.CurrentTime + " + executionTime + ";");
                    currentBlock.Line("toReturn.Target = target;");

                    currentBlock.Line("yield return toReturn;");
                    currentBlock = currentBlock.End();
                }
            }
        }
Exemplo n.º 10
0
        private static ICodeBlock GeneratePreloadStateContentForStateType(ICodeBlock codeBlock, IElement element, List<StateSave> list, string variableType)
        {
            if (list.Count != 0)
            {

                codeBlock = codeBlock.Function("public static void", "PreloadStateContent", variableType + " state, string contentManagerName");
                codeBlock.Line("ContentManagerName = contentManagerName;");

                codeBlock = codeBlock.Switch("state");

                // Loop through states here and access properties that need the values
                foreach (StateSave state in list)
                {
                    codeBlock = codeBlock.Case(variableType + "." + state.Name);
                    foreach (InstructionSave instruction in state.InstructionSaves)
                    {
                        if (instruction.Value != null && instruction.Value is string)
                        {
                            // We insert a block so that object throwaway is not redefined in the switch scope.
                            // We do this instead of making an object throwaway above the switch so that we don't
                            // get warnings if is nothing to load
                            codeBlock.Block().Line("object throwaway = " + GetRightSideAssignmentValueAsString(element, instruction) + ";");
                        }
                    }
                    codeBlock = codeBlock.End();

                }

                codeBlock = codeBlock.End();

                codeBlock = codeBlock.End();
            }
            return codeBlock;
        }
Exemplo n.º 11
0
        private static void WriteAnimationFields(IElement element, ICodeBlock codeBlock)
        {
            string ToQuotedSetName(string setValue)
            {
                if (setValue == null)
                {
                    return("null");
                }
                else
                {
                    return($"\"{setValue}\"");
                }
            }

            TopDownAnimationData animationData = null;
            var animationFilePath = MainController.GetAnimationFilePathFor(element as EntitySave);

            if (animationFilePath.Exists())
            {
                try
                {
                    var contents = System.IO.File.ReadAllText(animationFilePath.FullPath);
                    animationData = JsonConvert.DeserializeObject <TopDownAnimationData>(contents);
                }
                catch
                {
                    // do nothing, codegen will skip this
                }
            }

            var hasAnimationSets =
                animationData?.Animations.Count > 0;

            if (!hasAnimationSets)
            {
                codeBlock.Line("public List<TopDown.AnimationSet> AnimationSets { get; set; } = new List<TopDown.AnimationSet>();");
            }
            else
            {
                codeBlock.Line("public List<TopDown.AnimationSet> AnimationSets { get; set; } = new List<TopDown.AnimationSet>");

                var listBlock = codeBlock.Block();
                (listBlock.PostCodeLines[0] as CodeLine).Value += ";";

                foreach (var movementValueAnimation in animationData.Animations)
                {
                    string prefix = movementValueAnimation.MovementValuesName + "_";

                    foreach (var set in movementValueAnimation.AnimationSets)
                    {
                        var hasAnimations =
                            set.UpLeftAnimation != null ||
                            set.UpAnimation != null ||
                            set.UpRightAnimation != null ||
                            set.LeftAnimation != null ||
                            set.RightAnimation != null ||
                            set.DownLeftAnimation != null ||
                            set.DownAnimation != null ||
                            set.DownRightAnimation != null;

                        if (hasAnimations)
                        {
                            listBlock.Line($"new TopDown.AnimationSet()");
                            var assignmentBlock = listBlock.Block();
                            (assignmentBlock.PostCodeLines[0] as CodeLine).Value += ",";

                            string minSpeed =
                                set.AnimationSetName == "Idle" ? "0f" : ".1f";

                            assignmentBlock.Line($"MinSpeed = {minSpeed},");

                            assignmentBlock.Line($"MovementValueName = \"{movementValueAnimation.MovementValuesName}\",");



                            assignmentBlock.Line($"UpLeftAnimationName = {ToQuotedSetName(set.UpLeftAnimation)},");
                            assignmentBlock.Line($"UpAnimationName = {ToQuotedSetName(set.UpAnimation)},");
                            assignmentBlock.Line($"UpRightAnimationName = {ToQuotedSetName(set.UpRightAnimation)},");

                            assignmentBlock.Line($"LeftAnimationName = {ToQuotedSetName(set.LeftAnimation)},");
                            assignmentBlock.Line($"RightAnimationName = {ToQuotedSetName(set.RightAnimation)},");

                            assignmentBlock.Line($"DownLeftAnimationName = {ToQuotedSetName(set.DownLeftAnimation)},");
                            assignmentBlock.Line($"DownAnimationName = {ToQuotedSetName(set.DownAnimation)},");
                            assignmentBlock.Line($"DownRightAnimationName = {ToQuotedSetName(set.DownRightAnimation)}");
                        }
                    }
                }
            }
        }
        private void CreateInstructionForInterpolationRelative(StateCodeGeneratorContext context, ICodeBlock currentBlock, AnimatedStateSave previousState, AnimatedStateSave currentState)
        {
            if(previousState != null)
            {
                currentBlock.Line("var toReturn = new FlatRedBall.Instructions.DelegateInstruction(() =>");
                {
                    currentBlock = currentBlock.Block();

                    // Is the start clone necessary?
                    currentBlock.Line("var relativeStart = ElementSave.AllStates.FirstOrDefault(item => item.Name == \"" + previousState.StateName + "\").Clone();");
                    currentBlock.Line("var relativeEnd = ElementSave.AllStates.FirstOrDefault(item => item.Name == \"" + currentState.StateName + "\").Clone();");
                    currentBlock.Line("Gum.DataTypes.Variables.StateSaveExtensionMethods.SubtractFromThis(relativeEnd, relativeStart);");
                    currentBlock.Line("var difference = relativeEnd;");

                    string categoryName = "VariableState";
                    var category = context.Element.Categories.FirstOrDefault(item => item.States.Any(stateCandidate => stateCandidate.Name == currentState.StateName));

                    string enumValue = currentState.StateName;

                    if(currentState.StateName.Contains('/'))
                    {
                        var split = currentState.StateName.Split('/');

                        category = context.Element.Categories.FirstOrDefault(item => item.Name == split[0]);
                        enumValue = split[1];
                    }

                    if(category != null)
                    {
                        categoryName = category.Name;
                    }
                    currentBlock.Line("Gum.DataTypes.Variables.StateSave first = GetCurrentValuesOnState(" + categoryName + "." + enumValue + ");");

                    currentBlock.Line("Gum.DataTypes.Variables.StateSave second = first.Clone();");
                    currentBlock.Line("Gum.DataTypes.Variables.StateSaveExtensionMethods.AddIntoThis(second, difference);");


                    string interpolationTime = ToFloatString(currentState.Time - previousState.Time);

                    string easing = "FlatRedBall.Glue.StateInterpolation.Easing." + previousState.Easing;
                    string interpolationType = "FlatRedBall.Glue.StateInterpolation.InterpolationType." + previousState.InterpolationType;


                    currentBlock.Line(
                        string.Format("FlatRedBall.Glue.StateInterpolation.Tweener tweener = new FlatRedBall.Glue.StateInterpolation.Tweener(from: 0, to: 1, duration: {0}, type: {1}, easing: {2});",
                        interpolationTime,
                        interpolationType,
                        easing));

                    currentBlock.Line("tweener.Owner = this;");

                    currentBlock.Line("tweener.PositionChanged = newPosition => this.InterpolateBetween(first, second, newPosition);");
                    currentBlock.Line("tweener.Start();");
                    currentBlock.Line("StateInterpolationPlugin.TweenerManager.Self.Add(tweener);");


                    currentBlock = currentBlock.End();
                }
                currentBlock.Line(");");
                string previousStateTime = ToFloatString(previousState.Time);

                currentBlock.Line("toReturn.TimeToExecute = FlatRedBall.TimeManager.CurrentTime + " + previousStateTime + ";");
                currentBlock.Line("yield return toReturn;");
                
            }
        }
        private static void CreateInstructionForSubAnimation(ICodeBlock currentBlock, AnimationReferenceSave animationReferenceSave, AbsoluteOrRelative absoluteOrRelative, AnimationSave parentAnimation)
        {
            currentBlock = currentBlock.Block();

            //var instruction = new FlatRedBall.Instructions.DelegateInstruction(() =>
            //FlatRedBall.Instructions.InstructionManager.Instructions.AddRange(ClickableBushInstance.GrowAnimation));
            //instruction.TimeToExecute = FlatRedBall.TimeManager.CurrentTime + asdf;
            //yield return instruction;

            string animationName = animationReferenceSave.PropertyNameInCode();
                //animationReferenceSave. FlatRedBall.IO.FileManager.RemovePath(animationReferenceSave.Name) + "Animation";
            if(absoluteOrRelative == AbsoluteOrRelative.Relative)
            {
                animationName += "Relative";
            }

            currentBlock.Line($"var instruction = new FlatRedBall.Instructions.DelegateInstruction(()=>{animationName}.Play({parentAnimation.PropertyNameInCode()}));");
            currentBlock.Line("instruction.TimeToExecute = FlatRedBall.TimeManager.CurrentTime + " + ToFloatString(animationReferenceSave.Time) + ";");


            currentBlock.Line("yield return instruction;");
            currentBlock = currentBlock.End();
        }
        private void GenerateEnumerableFor(StateCodeGeneratorContext context, ICodeBlock currentBlock, AnimationSave animation, AbsoluteOrRelative absoluteOrRelative)
        {
            string animationType = "VariableState";

            string animationName = animation.PropertyNameInCode();

            if(absoluteOrRelative == AbsoluteOrRelative.Relative)
            {
                animationName += "Relative";
            }

            string propertyName = animationName + "Instructions";

            // Instructions used to be public - the user would grab them and add them to the InstructionManager,
            // but now everything is encased in an Animation object which handles stopping itself and provides a simple
            // Play method.
            if (animation.States.Count == 0 && animation.Animations.Count == 0)
            {
                currentBlock = currentBlock.Property("private System.Collections.Generic.IEnumerable<FlatRedBall.Instructions.Instruction>", propertyName).Get();

                currentBlock.Line("yield break;");

            }
            else if(absoluteOrRelative == AbsoluteOrRelative.Relative && animation.States.Count < 2 && animation.Animations.Count == 0)
            {

                currentBlock = currentBlock.Property("private System.Collections.Generic.IEnumerable<FlatRedBall.Instructions.Instruction>", propertyName).Get();

                currentBlock.Line("yield break;");
            }
            else
            {
                if (animation.States.Count != 0)
                {
                    var firstState = context.Element.AllStates.FirstOrDefault(item => item.Name == animation.States.First().StateName);

                    var category = context.Element.Categories.FirstOrDefault(item => item.States.Contains(firstState));

                    if (category != null)
                    {
                        animationType = category.Name;
                    }
                }

                currentBlock = currentBlock.Property("private System.Collections.Generic.IEnumerable<FlatRedBall.Instructions.Instruction>", propertyName).Get();

                GenerateOrderedStateAndSubAnimationCode(context, currentBlock, animation, animationType, absoluteOrRelative);

                if(animation.Loops)
                {
                    currentBlock = currentBlock.Block();

                    currentBlock.Line("var toReturn = new FlatRedBall.Instructions.DelegateInstruction(  " + 
                        "() => FlatRedBall.Instructions.InstructionManager.Instructions.AddRange(this." + propertyName + "));");
                    string executionTime = "0.0f";

                    if(animation.States.Count != 0)
                    {
                        executionTime = ToFloatString( animation.States.Last().Time);
                    }

                    currentBlock.Line("toReturn.TimeToExecute = FlatRedBall.TimeManager.CurrentTime + " + executionTime + ";");

                    currentBlock.Line("yield return toReturn;");
                    currentBlock = currentBlock.End();

                }
            }
            
        }
        private static void GenerateCsvDeserializationCode(ReferencedFileSave referencedFile, ICodeBlock codeBlock,  string variableName, string fileName, LoadType loadType)
        {
            #region Get the typeName (type as a string)

            string typeName;

            if (FileManager.GetExtension(fileName) == "csv" || referencedFile.TreatAsCsv)
            {
                // The CustomClass interface keeps a name just as it appears in Glue, so we want to use
                // the referencedFile.Name instead of the fileName because fileName will have "Content/" on it
                // and this shouldn't be the case for XNA 4 games
                typeName = CsvCodeGenerator.GetEntireGenericTypeForCsvFile(referencedFile);
            }

            else
            {
                typeName = "System.Collections.Generic.List<" + FileManager.RemovePath(FileManager.RemoveExtension(fileName)) + ">";
            }

            if (typeName.ToLower().EndsWith("file"))
            {
                typeName = typeName.Substring(0, typeName.Length - "file".Length);
            }
            #endregion

            #region Apply the delimiter change

            // Use the delimiter specified in Glue

            var block = codeBlock.Block();
            block.Line("// We put the { and } to limit the scope of oldDelimiter");
            block.Line("char oldDelimiter = FlatRedBall.IO.Csv.CsvFileManager.Delimiter;");

            char delimiterAsChar = referencedFile.CsvDelimiter.ToChar();

            block.Line(@"FlatRedBall.IO.Csv.CsvFileManager.Delimiter = '" + delimiterAsChar + "';");

            #endregion

            string whatToLoadInto;
            if (loadType == LoadType.CompleteLoad)
            {
                whatToLoadInto = "temporaryCsvObject";
                block.Line(string.Format("{0} {1} = new {0}();", typeName, whatToLoadInto));
            }
            else
            {
                whatToLoadInto = referencedFile.GetInstanceName();
                block.Line(string.Format("{0}.Clear();", whatToLoadInto));
            }

            #region Call CsvFileManager.CsvDeserializeList/Dictionary

            if (referencedFile.CreatesDictionary)
            {
                string keyType;
                string valueType;

                CsvCodeGenerator.GetDictionaryTypes(referencedFile, out keyType, out valueType);

                if (keyType == null)
                {
                    System.Windows.Forms.MessageBox.Show("Could not find the key type for:\n\n" + referencedFile.Name + "\n\nYou need to mark one of the headers as required or not load this file as a dictionary.");
                    keyType = "UNKNOWN_TYPE";

                }
                // CsvFileManager.CsvDeserializeDictionary<string, CarData>("Content/CarData.csv", carDataDictionary);
                block.Line(string.Format("FlatRedBall.IO.Csv.CsvFileManager.CsvDeserializeDictionary<{2}, {3}>(\"{0}\", {1});", ProjectBase.AccessContentDirectory + fileName,
                                  whatToLoadInto, keyType, valueType));
            }
            else
            {
                string elementType = referencedFile.GetTypeForCsvFile();

                block.Line(string.Format("FlatRedBall.IO.Csv.CsvFileManager.CsvDeserializeList(typeof({0}), \"{1}\", {2});",
                                         elementType, ProjectBase.AccessContentDirectory + fileName, whatToLoadInto));
            }

            #endregion

            block.Line("FlatRedBall.IO.Csv.CsvFileManager.Delimiter = oldDelimiter;");

            if (loadType == LoadType.CompleteLoad)
            {
                block.Line(string.Format("{0} = temporaryCsvObject;", variableName));
            }
        }
Exemplo n.º 16
0
        private static ICodeBlock CreateClassForStateCategory(ICodeBlock currentBlock, List <StateSave> statesForThisCategory, string categoryClassName, IElement element)
        {
            if (statesForThisCategory.Count != 0)
            {
                string prefix = "public";

                string postfix = null;
                if (IsStateDefinedInBase(element, categoryClassName))
                {
                    postfix = $" : {element.BaseElement.Replace("\\", ".")}.{categoryClassName}";
                }


                currentBlock = currentBlock.Class(prefix, categoryClassName, postfix);

                currentBlock.Line($"public string Name;");

                foreach (var variable in element.CustomVariables)
                {
                    // todo - pass the category here and skip over excluded variables
                    var isExcluded = false;
                    if (!isExcluded)
                    {
                        string type = variable.Type;

                        if (variable.GetIsFile())
                        {
                            type = "string";
                        }
                        else
                        {
                            type = CustomVariableCodeGenerator.GetMemberTypeFor(variable, element);
                        }
                        currentBlock.Line($"public {type} {variable.Name};");
                    }
                }


                for (int i = 0; i < statesForThisCategory.Count; i++)
                {
                    var state = statesForThisCategory[i];

                    currentBlock.Line($"public static {categoryClassName} {state.Name} = new {categoryClassName}()");
                    var variableBlock = currentBlock.Block();

                    variableBlock.Line($"Name = \"{state.Name}\",");

                    foreach (var instruction in state.InstructionSaves)
                    {
                        if (instruction.Value != null)
                        {
                            var rightSide        = GetRightSideAssignmentValueAsString(element, instruction);
                            var matchingVariable = element.GetCustomVariableRecursively(instruction.Member);
                            if (matchingVariable?.GetIsFile() == true)
                            {
                                // If it's a file we are only going to reference the file name here as to not preload the file
                                rightSide = $"\"{rightSide}\"";
                            }

                            variableBlock.Line($"{instruction.Member} = {rightSide},");
                        }
                    }
                    variableBlock.End().Line(";");
                }
                currentBlock = currentBlock.End();
            }
            return(currentBlock);
        }
Exemplo n.º 17
0
        private void CreateInstructionForInterpolationRelative(StateCodeGeneratorContext context, ICodeBlock currentBlock, AnimatedStateSave previousState, AnimatedStateSave currentState)
        {
            if (previousState != null)
            {
                currentBlock.Line("var toReturn = new FlatRedBall.Instructions.DelegateInstruction(() =>");
                {
                    currentBlock = currentBlock.Block();

                    // Is the start clone necessary?
                    currentBlock.Line("var relativeStart = ElementSave.AllStates.FirstOrDefault(item => item.Name == \"" + previousState.StateName + "\").Clone();");
                    currentBlock.Line("var relativeEnd = ElementSave.AllStates.FirstOrDefault(item => item.Name == \"" + currentState.StateName + "\").Clone();");
                    currentBlock.Line("Gum.DataTypes.Variables.StateSaveExtensionMethods.SubtractFromThis(relativeEnd, relativeStart);");
                    currentBlock.Line("var difference = relativeEnd;");

                    string categoryName = "VariableState";
                    var    category     = context.Element.Categories.FirstOrDefault(item => item.States.Any(stateCandidate => stateCandidate.Name == currentState.StateName));

                    string enumValue = currentState.StateName;

                    if (currentState.StateName.Contains('/'))
                    {
                        var split = currentState.StateName.Split('/');

                        category  = context.Element.Categories.FirstOrDefault(item => item.Name == split[0]);
                        enumValue = split[1];
                    }

                    if (category != null)
                    {
                        categoryName = category.Name;
                    }
                    currentBlock.Line("Gum.DataTypes.Variables.StateSave first = GetCurrentValuesOnState(" + categoryName + "." + enumValue + ");");

                    currentBlock.Line("Gum.DataTypes.Variables.StateSave second = first.Clone();");
                    currentBlock.Line("Gum.DataTypes.Variables.StateSaveExtensionMethods.AddIntoThis(second, difference);");


                    string interpolationTime = ToFloatString(currentState.Time - previousState.Time);

                    string easing            = "FlatRedBall.Glue.StateInterpolation.Easing." + previousState.Easing;
                    string interpolationType = "FlatRedBall.Glue.StateInterpolation.InterpolationType." + previousState.InterpolationType;


                    currentBlock.Line(
                        string.Format("FlatRedBall.Glue.StateInterpolation.Tweener tweener = new FlatRedBall.Glue.StateInterpolation.Tweener(from: 0, to: 1, duration: {0}, type: {1}, easing: {2});",
                                      interpolationTime,
                                      interpolationType,
                                      easing));

                    currentBlock.Line("tweener.Owner = this;");

                    currentBlock.Line("tweener.PositionChanged = newPosition => this.InterpolateBetween(first, second, newPosition);");
                    currentBlock.Line("tweener.Start();");
                    currentBlock.Line("StateInterpolationPlugin.TweenerManager.Self.Add(tweener);");


                    currentBlock = currentBlock.End();
                }
                currentBlock.Line(");");
                string previousStateTime = ToFloatString(previousState.Time);

                currentBlock.Line("toReturn.TimeToExecute = FlatRedBall.TimeManager.CurrentTime + " + previousStateTime + ";");
                currentBlock.Line("toReturn.Target = target;");

                currentBlock.Line("yield return toReturn;");
            }
        }
        private void CreateInstructionForInterpolation(StateCodeGeneratorContext context, ICodeBlock currentBlock, string animationType, AnimatedStateSave previousState, AnimatedStateSave currentState, AbsoluteOrRelative absoluteOrRelative, string animationName)
        {

            currentBlock = currentBlock.Block();

            if (absoluteOrRelative == AbsoluteOrRelative.Absolute)
            {

                CreateInstructionForInterpolationAbsolute(context, currentBlock, animationType, previousState, currentState, animationName);
            }
            else
            {
                CreateInstructionForInterpolationRelative(context,currentBlock,  previousState, currentState);
            }
            currentBlock = currentBlock.End();
        }