private void GenerateVariable(ICodeBlock currentBlock, string propertyName, Gum.DataTypes.Variables.VariableSave variable, ElementSave elementSave)
        {
            #region Get Variable Type
            string variableType = variable.Type;

            string unmodifiedVariableType = variableType;

            if (GueDerivingClassCodeGenerator.Self.TypeToQualifiedTypes.ContainsKey(variableType))
            {
                variableType = GueDerivingClassCodeGenerator.Self.TypeToQualifiedTypes[variableType];
            }

            if (variable.IsFile && variable.GetRootName() == "SourceFile")
            {
                variableType = "Microsoft.Xna.Framework.Graphics.Texture2D";
            }

            #endregion

            ICodeBlock property = currentBlock.Property("public " + variableType, variable.Name.Replace(" ", ""));


            string variableName = variable.Name;
            if (mStandardVariableNameAliases.ContainsKey(variableName.Replace(" ", "")))
            {
                variableName = mStandardVariableNameAliases[variableName.Replace(" ", "")];
            }

            string whatToGetOrSet = propertyName + "." + variableName.Replace(" ", "");

            GenerateGetter(propertyName, variable, property, variableName, whatToGetOrSet, elementSave);

            GenerateSetter(propertyName, variable, property, variableName, whatToGetOrSet, elementSave);
        }
예제 #2
0
        private void AdjustEnumerationVariableValue(Gum.DataTypes.Variables.VariableSave variableSave, ElementSave element, ref string variableValue, ref string variableType)
        {
            if (variableSave.Type == "Gum.Managers.PositionUnitType" || variableSave.Type == "PositionUnitType")
            {
                string rootName = variableSave.GetRootName();

                // convert from PositionUnitType to GeneralUnitType

                GeneralUnitType convertedValue =
                    UnitConverter.ConvertToGeneralUnit((PositionUnitType)variableSave.Value);

                variableValue = convertedValue.ToString();

                variableType = "Gum.Converters.GeneralUnitType";
            }

            string prefix = variableType;



            if (mTypeToQualifiedTypes.ContainsKey(prefix))
            {
                prefix = mTypeToQualifiedTypes[prefix];
            }
            else
            {
                ModifyVariableTypeForProperty(ref prefix, variableSave, element);
            }

            variableValue = prefix + "." + variableValue;
        }
예제 #3
0
        private static object AddValue(VariableSave firstVariable, VariableSave secondVariable)
        {
            if (firstVariable.Value == null || secondVariable.Value == null)
            {
                return(secondVariable.Value);
            }
            else if (firstVariable.Value is float && secondVariable.Value is float)
            {
                float firstFloat  = (float)firstVariable.Value;
                float secondFloat = (float)secondVariable.Value;

                return(firstFloat + secondFloat);
            }
            else if (firstVariable.Value is double && secondVariable.Value is double)
            {
                double firstDouble  = (double)firstVariable.Value;
                double secondDouble = (double)secondVariable.Value;

                return(firstDouble + secondDouble);
            }

            else if (firstVariable.Value is int)
            {
                int firstInt  = (int)firstVariable.Value;
                int secondInt = (int)secondVariable.Value;

                return(firstInt + secondInt);
            }
            else
            {
                return(secondVariable.Value);
            }
        }
예제 #4
0
        // I wrote this for animation but it turns out it isn't going to work how I expected
        //public static StateSave CombineBaseValuesAndClone(this StateSave stateSave)
        //{
        //    StateSave cloned = new StateSave();

        //    if (stateSave.ParentContainer == null)
        //    {
        //        // This thing doesn't have a parent container so we have no idea how to get the default and follow inheritance
        //        cloned = stateSave.Clone();
        //    }
        //    else
        //    {
        //        ElementSave parent = stateSave.ParentContainer;
        //        if (parent.DefaultState == stateSave)
        //        {
        //            if (string.IsNullOrEmpty(parent.BaseType))
        //            {
        //                cloned = stateSave.Clone();
        //            }
        //            else
        //            {
        //                ElementSave baseOfParent = ObjectFinder.Self.GetElementSave(parent.BaseType);

        //                if (baseOfParent == null)
        //                {
        //                    cloned = stateSave.Clone();
        //                }
        //                else
        //                {
        //                    cloned = baseOfParent.DefaultState.CombineBaseValuesAndClone();

        //                    cloned.MergeIntoThis(stateSave);

        //                }
        //            }
        //        }
        //        else
        //        {
        //            cloned = parent.DefaultState.CombineBaseValuesAndClone();

        //            cloned.MergeIntoThis(stateSave);
        //        }
        //    }


        //    return cloned;

        //}

        public static void Merge(StateSave firstState, StateSave secondState, float otherRatio, List <VariableSaveValues> mergedValues)
        {
#if DEBUG
            if (firstState == null || secondState == null)
            {
                throw new ArgumentNullException("States must not be null");
            }
#endif

            foreach (var secondVariable in secondState.Variables)
            {
                object secondValue = secondVariable.Value;

                VariableSave firstVariable = firstState.GetVariableSave(secondVariable.Name);

                // If this variable doesn't have a value, or if the variable doesn't set the variable
                // then we need to go recursive to see what the value is:
                bool needsValueFromBase = firstVariable == null || firstVariable.SetsValue == false;
                bool setsValue          = secondVariable.SetsValue;

                object firstValue = null;

                if (firstVariable == null)
                {
                    firstValue = secondVariable.Value;

                    // Get the value recursively before adding it to the list
                    if (needsValueFromBase)
                    {
                        var variableOnThis = firstState.GetVariableSave(secondVariable.Name);
                        if (variableOnThis != null)
                        {
                            setsValue |= variableOnThis.SetsValue;
                        }

                        firstValue = firstState.GetValueRecursive(secondVariable.Name);
                    }
                }
                else
                {
                    firstValue = firstVariable.Value;
                }

                if (setsValue)
                {
                    object interpolated = GetValueConsideringInterpolation(firstValue, secondValue, otherRatio);

                    VariableSaveValues value = new VariableSaveValues();
                    value.Name  = secondVariable.Name;
                    value.Value = interpolated;

                    mergedValues.Add(value);
                }
            }

            // todo:  Handle lists?
        }
예제 #5
0
        // If adding stuff here, make sure to add to the Clone method!


        public VariableSave Clone()
        {
            VariableSave toReturn = (VariableSave)this.MemberwiseClone();

            toReturn.CustomTypeConverter   = this.CustomTypeConverter;
            toReturn.ExcludedValuesForEnum = new List <object>();
            toReturn.ExcludedValuesForEnum.AddRange(this.ExcludedValuesForEnum);


            return(toReturn);
        }
        private bool GetIfShouldGenerateProperty(Gum.DataTypes.Variables.VariableSave variable, ElementSave standardElementSave)
        {
            string variableName = variable.GetRootName();

            if (mVariableNamesToSkipForProperties.Contains(variableName))
            {
                return(false);
            }

            return(true);
        }
예제 #7
0
        public void SetValue(string variableName, object valueToSet, string variableType)
        {
            VariableSave variableState = GetVariableSave(variableName);

            if (variableState == null)
            {
                variableState      = new VariableSave();
                variableState.Name = variableName;
                variableState.Type = variableType;
                this.Variables.Add(variableState);
            }

            variableState.Value     = valueToSet;
            variableState.SetsValue = true;
        }
예제 #8
0
        public static void SubtractFromThis(this StateSave thisState, StateSave other)
        {
            foreach (var variableSave in other.Variables)
            {
                // The first will use its default if one doesn't exist
                VariableSave whatToSet = thisState.GetVariableSave(variableSave.Name);

                if (whatToSet != null && (whatToSet.SetsValue || variableSave.SetsValue))
                {
                    whatToSet.SetsValue = true;
                    whatToSet.Value     = SubtractValue(whatToSet, variableSave);
                }
            }

            // todo:  Handle lists?
        }
예제 #9
0
        private bool GetIfShouldGenerateProperty(Gum.DataTypes.Variables.VariableSave variable, ElementSave standardElementSave)
        {
            string variableName = variable.GetRootName();

            if (mVariableNamesToSkipForProperties.Contains(variableName))
            {
                return(false);
            }
            // Core Gum objets don't have states, so if it's a state then don't create a property for it - it'll be handled
            // by the code that handles states
            if (variable.IsState(standardElementSave))
            {
                return(false);
            }

            return(true);
        }
예제 #10
0
        public static VariableSave GetVariableRecursive(this StateSave stateSave, string variableName)
        {
            VariableSave variableSave = stateSave.GetVariableSave(variableName);

            if (variableSave == null)
            {
                // Is this thing the default?
                ElementSave parent = stateSave.ParentContainer;

                if (parent != null && stateSave != parent.DefaultState)
                {
                    variableSave = stateSave.GetVariableSave(variableName);

                    if (variableSave == null)
                    {
                        variableSave = parent.DefaultState.GetVariableSave(variableName);
                    }
                }

                if (variableSave == null && parent != null)
                {
                    ElementSave baseElement = GetBaseElementFromVariable(variableName, parent);

                    if (baseElement != null)
                    {
                        string nameInBase = variableName;

                        if (variableName.Contains('.'))
                        {
                            // this variable is set on an instance, but we're going into the
                            // base type, so we want to get the raw variable and not the variable
                            // as tied to an instance.
                            nameInBase = variableName.Substring(nameInBase.IndexOf('.') + 1);
                        }

                        return(baseElement.DefaultState.GetVariableRecursive(nameInBase));
                    }
                }

                return(variableSave);
            }
            else
            {
                return(variableSave);
            }
        }
예제 #11
0
        public static void MergeIntoThis(this StateSave thisState, StateSave other, float otherRatio = 1)
        {
#if DEBUG
            if (other == null)
            {
                throw new ArgumentNullException("other Statesave is null and it shouldn't be");
            }
#endif

            foreach (var variableSave in other.Variables)
            {
                // The first will use its default if one doesn't exist
                VariableSave whatToSet = thisState.GetVariableSave(variableSave.Name);

                // If this variable doesn't have a value, or if the variable doesn't set the variable
                // then we need to go recursive to see what the value is:
                bool needsValueFromBase = whatToSet == null || whatToSet.SetsValue == false;
                bool setsValue          = variableSave.SetsValue;


                if (whatToSet == null)
                {
                    whatToSet = variableSave.Clone();

                    // Get the value recursively before adding it to the list
                    if (needsValueFromBase)
                    {
                        var variableOnThis = thisState.GetVariableSave(variableSave.Name);
                        if (variableOnThis != null)
                        {
                            setsValue |= variableOnThis.SetsValue;
                        }
                        whatToSet.Value = thisState.GetValueRecursive(variableSave.Name);
                    }

                    thisState.Variables.Add(whatToSet);
                }


                whatToSet.SetsValue = setsValue;
                whatToSet.Value     = GetValueConsideringInterpolation(whatToSet.Value, variableSave.Value, otherRatio);
            }

            // todo:  Handle lists?
        }
예제 #12
0
        internal bool ShouldExclude(VariableSave defaultVariable, RecursiveVariableFinder rvf)
        {
            bool shouldExclude = false;
            foreach (var plugin in this.Plugins.Where(item=>this.PluginContainers[item].IsEnabled))
            {
                PluginContainer container = this.PluginContainers[plugin];

                if (container.Plugin is PluginBase)
                {

                    try
                    {
                        shouldExclude |= ((PluginBase)container.Plugin).GetIfVariableIsExcluded(defaultVariable, rvf);
                    }
                    catch (Exception e)
                    {
                        container.Fail(e, "Failed in GetIfVariableIsExcluded");
                    }
                }
            }
            return shouldExclude;
        }
예제 #13
0
        /// <summary>
        /// Assigns a value to a variable.  If the variable doesn't exist then the variable is instantiated, then the value is assigned.
        /// </summary>
        /// <param name="stateSave">The StateSave that contains the variable.  The variable will be added to this StateSave if it doesn't exist.</param>
        /// <param name="variableName">The name of the variable to look for.</param>
        /// <param name="value">The value to assign to the variable.</param>
        /// <param name="instanceSave">The instance that owns this variable.  This may be null.</param>
        /// <param name="variableType">The type of the variable.  This is only needed if the value is null.</param>
        private static VariableSave AssignVariableSave(this StateSave stateSave, string variableName, object value,
                                                       InstanceSave instanceSave, string variableType = null, bool isFile = false)
        {
            // Not a reserved variable, so use the State's variables
            VariableSave variableSave = stateSave.GetVariableSave(variableName);

            if (variableSave == null)
            {
                variableSave = new VariableSave();

                // If the variableType is not null, give it priority
                if (!string.IsNullOrEmpty(variableType))
                {
                    variableSave.Type = variableType;
                }

                else if (value is bool)
                {
                    variableSave.Type = "bool";
                }
                else if (value is float)
                {
                    variableSave.Type = "float";
                }
                else if (value is int)
                {
                    variableSave.Type = "int";
                }
                else if (value is int?)
                {
                    variableSave.Type = "int?";
                }
                // account for enums
                else if (value is string)
                {
                    variableSave.Type = "string";
                }
                else if (value == null)
                {
                    variableSave.Type = variableType;
                }
                else
                {
                    variableSave.Type = value.GetType().ToString();
                }

                variableSave.IsFile = isFile;

                variableSave.Name = variableName;

                stateSave.Variables.Add(variableSave);
            }



            // There seems to be
            // two ways to indicate
            // that a variable has a
            // source object.  One is
            // to pass a InstanceSave to
            // this method, another is to
            // include a '.' in the name.  If
            // an instanceSave is passed, then
            // a dot MUST be present.  I don't think
            // we allow a dot to exist without a variable
            // representing a variable on an instance save,
            // so I'm not sure why we even require an InstanceSave.
            // Also, it seems like code (especially plugins) may not
            // know to pass an InstanceSave and may assume that the dot
            // is all that's needed.  If so, we shouldn't be strict and require
            // a non-null InstanceSave.
            //if (instanceSave != null)
            // Update:  We used to only check this when first creating a Variable, but
            // there's no harm in forcing the source object.  Let's do that.
            // Update:  Turns out we do need the instance so that we can get the base type
            // to find out if the variable IsFile or not.  If the InstanceSave is null, but
            // we have a sourceObjectName that we determine by the presence of a dot, then let's
            // try to find the InstanceSave
            if (StringFunctions.ContainsNoAlloc(variableName, '.'))
            {
                string rootName         = variableSave.Name.Substring(variableSave.Name.IndexOf('.') + 1);
                string sourceObjectName = variableSave.Name.Substring(0, variableSave.Name.IndexOf('.'));

                if (instanceSave == null && stateSave.ParentContainer != null)
                {
                    instanceSave = stateSave.ParentContainer.GetInstance(sourceObjectName);
                }

                //ElementSave baseElement = ObjectFinder.Self.GetRootStandardElementSave(instanceSave);

                //VariableSave baseVariableSave = baseElement.DefaultState.GetVariableSave(rootName);
                if (instanceSave != null)
                {
                    // can we get this from the base element?
                    var  instanceBase = ObjectFinder.Self.GetElementSave(instanceSave);
                    bool found        = false;

                    if (instanceBase != null)
                    {
                        VariableSave baseVariableSave = instanceBase.DefaultState.Variables.FirstOrDefault(item => item.ExposedAsName == rootName || item.Name == rootName);
                        if (baseVariableSave != null)
                        {
                            variableSave.IsFile = baseVariableSave.IsFile;
                            found = true;
                        }
                    }

                    if (!found)
                    {
                        VariableSave baseVariableSave = ObjectFinder.Self.GetRootStandardElementSave(instanceSave).DefaultState.GetVariableSave(rootName);
                        if (baseVariableSave != null)
                        {
                            variableSave.IsFile = baseVariableSave.IsFile;
                        }
                    }
                }
            }

            variableSave.SetsValue = true;

            variableSave.Value = value;

            return(variableSave);
        }
예제 #14
0
        private bool GetIfShouldGenerateStateVariable(Gum.DataTypes.Variables.VariableSave variable, ElementSave container)
        {
            bool toReturn = true;

            string variableName = variable.GetRootName();



            if (variable.Value == null || !variable.SetsValue)
            {
                toReturn = false;
            }
            // states can't set states on this
            if (variable.IsState(container) && string.IsNullOrEmpty(variable.SourceObject))
            {
                toReturn = false;
            }

            if (toReturn && mVariableNamesToSkipForStates.Contains(variableName))
            {
                toReturn = false;
            }

            bool hasSourceObject = !string.IsNullOrEmpty(variable.SourceObject);

            if (toReturn && hasSourceObject)
            {
                InstanceSave instanceSave = container.GetInstance(variable.SourceObject);

                if (instanceSave == null)
                {
                    toReturn = false;
                }
                else
                {
                    var baseElement = Gum.Managers.ObjectFinder.Self.GetElementSave(instanceSave.BaseType);

                    if (baseElement == null)
                    {
                        toReturn = false;
                    }

                    if (toReturn)
                    {
                        // Gum (just like Glue) keeps variables that aren't needed around.  This allows users to rename things and not lose
                        // important information accidentally.  But because of that we have to make sure that the variable we're working with is
                        // valid for the type of object we're dealing with.
                        var defaultState = baseElement.DefaultState;

                        RecursiveVariableFinder rvf = new RecursiveVariableFinder(defaultState);

                        var foundVariable = rvf.GetVariable(variable.GetRootName());

                        if (foundVariable == null)
                        {
                            // This doesn't exist anywhere in the inheritance chain, so we don't want to generate it:
                            toReturn = false;
                        }
                    }
                }
            }

            if (toReturn && !hasSourceObject)
            {
                // If a variable is part of a component, it better be defined in the base type or else we won't generate it.
                // For example, consider a component that used to inherit from Text. It will have variables for fonts. If that
                // component switches to inheriting from Sprite, those variables will still exist in the XML for that component,
                // but we shouldn't generate any state variables for those variables. So we'll go to the base type and see if those
                // variables exist
                bool isComponent = container is ComponentSave;

                var rootComponent = Gum.Managers.ObjectFinder.Self.GetRootStandardElementSave(container);

                // If the Container is a Screen, then rootComponent will be null, so we don't need to do anything
                if (rootComponent == null)
                {
                    toReturn = false;
                }
                else
                {
                    IEnumerable <VariableSave> variablesToCheck;

                    if (isComponent)
                    {
                        var component = Gum.Managers.ObjectFinder.Self.GetStandardElement("Component");

                        variablesToCheck = rootComponent.DefaultState.Variables.Concat(component.DefaultState.Variables);
                    }
                    else
                    {
                        var defaultState = rootComponent.DefaultState;

                        variablesToCheck = defaultState.Variables;
                    }


                    bool wasMatchFound = variablesToCheck.Any(item => item.Name == variable.GetRootName());
                    toReturn = wasMatchFound;
                }
            }



            return(toReturn);
        }
예제 #15
0
        /// <summary>
        /// Returns the first instance of an existing VariableSave recursively.
        /// </summary>
        /// <param name="stateSave">The possible state that contains the variable. If it doesn't, then the code will recursively go to base types.</param>
        /// <param name="variableName"></param>
        /// <returns></returns>
        public static VariableSave GetVariableRecursive(this StateSave stateSave, string variableName)
        {
            VariableSave variableSave = stateSave.GetVariableSave(variableName);

            if (variableSave == null)
            {
                // 1. Go to the default state if it's not a default
                bool shouldGoToDefaultState = false;
                // 2. Go to the base type if the variable is on the container itself, or if the instance is DefinedByBase
                bool shouldGoToBaseType = false;
                // 3. Go to the instance if it's on an instance and we're not going to the default state or base type
                bool shouldGoToInstanceComponent = false;

                // Is this thing the default?
                ElementSave elementContainingState = stateSave.ParentContainer;

                if (elementContainingState != null)
                {
                    if (elementContainingState != null && stateSave != elementContainingState.DefaultState)
                    {
                        shouldGoToDefaultState = true;
                    }

                    var          isVariableOnInstance = variableName.Contains('.');
                    InstanceSave instance             = null;
                    bool         canGoToBase          = false;

                    var hasBaseType = !string.IsNullOrEmpty(elementContainingState.BaseType);
                    var isVariableDefinedOnThisInheritanceLevel = false;

                    var instanceName = VariableSave.GetSourceObject(variableName);
                    instance = elementContainingState.Instances.FirstOrDefault(item => item.Name == instanceName);

                    if (isVariableOnInstance && hasBaseType)
                    {
                        if (instance != null && instance.DefinedByBase == false)
                        {
                            isVariableDefinedOnThisInheritanceLevel = true;
                        }
                    }
                    else if (!hasBaseType)
                    {
                        isVariableDefinedOnThisInheritanceLevel = true;
                    }

                    canGoToBase = isVariableOnInstance == false ||
                                  isVariableDefinedOnThisInheritanceLevel == false;

                    if (!shouldGoToDefaultState)
                    {
                        shouldGoToBaseType = canGoToBase;
                    }

                    if (!shouldGoToDefaultState && !shouldGoToBaseType)
                    {
                        shouldGoToInstanceComponent = isVariableOnInstance;
                    }


                    if (shouldGoToDefaultState)
                    {
                        variableSave = elementContainingState.DefaultState.GetVariableSave(variableName);
                        if (variableSave == null)
                        {
                            shouldGoToBaseType = canGoToBase;
                        }
                    }

                    if (shouldGoToBaseType)
                    {
                        var baseElement = ObjectFinder.Self.GetElementSave(elementContainingState.BaseType);

                        if (baseElement != null)
                        {
                            variableSave = baseElement.DefaultState.GetVariableRecursive(variableName);
                        }
                    }
                    else if (shouldGoToInstanceComponent)
                    {
                        ElementSave instanceElement = null;
                        if (instance != null)
                        {
                            instanceElement = ObjectFinder.Self.GetElementSave(instance);
                        }

                        if (instanceElement != null)
                        {
                            variableSave = instanceElement.DefaultState.GetVariableRecursive(VariableSave.GetRootName(variableName));
                        }
                    }
                }
            }

            return(variableSave);
        }
예제 #16
0
        public static void SetValue(this StateSave stateSave, string variableName, object value,
                                    InstanceSave instanceSave = null, string variableType = null)
        {
            bool isReservedName = TrySetReservedValues(stateSave, variableName, value, instanceSave);

            VariableSave variableSave           = stateSave.GetVariableSave(variableName);
            var          coreVariableDefinition = stateSave.GetVariableRecursive(variableName);

            string exposedVariableSourceName = null;

            if (!string.IsNullOrEmpty(coreVariableDefinition?.ExposedAsName) && instanceSave == null)
            {
                exposedVariableSourceName = coreVariableDefinition.Name;
            }
            string rootName = variableName;

            if (StringFunctions.ContainsNoAlloc(variableName, '.'))
            {
                rootName = variableName.Substring(variableName.IndexOf('.') + 1);
            }



            if (!isReservedName)
            {
                bool isFile = false;

                // Why might instanceSave be null?
                // The reason is because StateSaves
                // are used both for actual game data
                // as well as temporary variable containers.
                // If a StateSave is a temporary container then
                // instanceSave may (probably will be) null.
                if (instanceSave != null)
                {
                    VariableSave temp = variableSave;
                    if (variableSave == null)
                    {
                        temp      = new VariableSave();
                        temp.Name = variableName;
                    }
                    isFile = temp.GetIsFileFromRoot(instanceSave);
                }
                else
                {
                    VariableSave temp = variableSave;
                    if (variableSave == null)
                    {
                        temp      = new VariableSave();
                        temp.Name = variableName;
                    }
                    isFile = temp.GetIsFileFromRoot(stateSave.ParentContainer);
                }


                if (value != null && value is IList)
                {
                    stateSave.AssignVariableListSave(variableName, value, instanceSave);
                }
                else
                {
                    variableSave = stateSave.AssignVariableSave(variableName, value, instanceSave, variableType, isFile);

                    variableSave.IsFile = isFile;

                    if (!string.IsNullOrEmpty(exposedVariableSourceName))
                    {
                        variableSave.ExposedAsName = variableName;
                        variableSave.Name          = exposedVariableSourceName;
                    }

                    stateSave.Variables.Sort((first, second) => first.Name.CompareTo(second.Name));
                }



                if (isFile &&
                    value is string &&
                    !FileManager.IsRelative((string)value))
                {
                    string directoryToMakeRelativeTo = FileManager.GetDirectory(ObjectFinder.Self.GumProjectSave.FullFileName);

                    const bool preserveCase = true;
                    value = FileManager.MakeRelative((string)value, directoryToMakeRelativeTo, preserveCase);

                    // re-assign the value using the relative name now
                    var assignedVariable = stateSave.AssignVariableSave(variableName, value, instanceSave, variableType, isFile);
                }
            }
        }
        private InterpolationCharacteristic GetInterpolationCharacteristic(VariableSave variableSave, ElementSave container)
        {
            string variableType = null;
            if (variableSave != null)
            {
                variableType = variableSave.Type;
            }


            if (variableSave != null && variableSave.IsState(container))
            {

                ElementSave categoryContainer;
                StateSaveCategory stateSaveCategory;

                if (variableSave.IsState(container, out categoryContainer, out stateSaveCategory, recursive: false))
                {
                    return InterpolationCharacteristic.CanInterpolate;
                }
                else
                {
                    // it's an exposed variable which cant be interpolated currently
                    return InterpolationCharacteristic.CantInterpolate;
                }
            }

            if (variableSave == null ||
                variableType == null ||
                variableType == "string" ||
                variableType == "bool" ||
                variableType == "Color" ||
                variableSave.IsFile
                )
            {
                return InterpolationCharacteristic.CantInterpolate;
            }

            if (variableType == "float" || variableType == "int" || variableType == "double" || variableType == "byte")
            {
                return InterpolationCharacteristic.CanInterpolate;
            }
            return InterpolationCharacteristic.CantInterpolate;

        }
예제 #18
0
        public static void SetValue(this StateSave stateSave, string variableName, object value, InstanceSave instanceSave = null, string variableType = null)
        {
            bool isReservedName = TrySetReservedValues(stateSave, variableName, value, instanceSave);

            VariableSave variableSave = stateSave.GetVariableSave(variableName);

            string exposedVariableSourceName = null;

            string rootName = variableName;

            if (variableName.Contains('.'))
            {
                rootName = variableName.Substring(variableName.IndexOf('.') + 1);
            }
            else if (stateSave.ParentContainer != null && stateSave.ParentContainer.DefaultState != stateSave)
            {
                // This isn't the default state, so let's ask the default state if this is an exposed variable...
                var defaultState = stateSave.ParentContainer.DefaultState;

                var found = defaultState.Variables.FirstOrDefault(item => item.ExposedAsName == variableName);
                if (found != null)
                {
                    exposedVariableSourceName = found.Name;
                }
            }

            if (!isReservedName)
            {
                if (value != null && value is IList)
                {
                    stateSave.AssignVariableListSave(variableName, value, instanceSave);
                }
                else
                {
                    variableSave = stateSave.AssignVariableSave(variableName, value, instanceSave, variableType);

                    if (!string.IsNullOrEmpty(exposedVariableSourceName))
                    {
                        variableSave.ExposedAsName = variableName;
                        variableSave.Name          = exposedVariableSourceName;
                    }

                    stateSave.Variables.Sort((first, second) => first.Name.CompareTo(second.Name));
                }


                bool isFile = false;

                // Why might instanceSave be null?
                // The reason is because StateSaves
                // are used both for actual game data
                // as well as temporary variable containers.
                // If a StateSave is a temporary container then
                // instanceSave may (probably will be) null.
                if (instanceSave != null)
                {
                    isFile = variableSave.GetIsFileFromRoot(instanceSave);
                }
                else if (variableSave != null)
                {
                    isFile = variableSave.IsFile;
                }

                if (isFile &&
                    value is string &&
                    !FileManager.IsRelative((string)value))
                {
                    string directoryToMakeRelativeTo = FileManager.GetDirectory(ObjectFinder.Self.GumProjectSave.FullFileName);

                    const bool preserveCase = true;
                    value = FileManager.MakeRelative((string)value, directoryToMakeRelativeTo, preserveCase);

                    // re-assign the value using the relative name now
                    stateSave.AssignVariableSave(variableName, value, instanceSave, variableType);
                }
            }
        }
예제 #19
0
        /// <summary>
        /// Adjusts a variable value to be code which can execute properly. For example, converts a file string to a load call.
        /// </summary>
        /// <param name="variableSave">The variable</param>
        /// <param name="container">The container of the variable</param>
        /// <param name="variableValue">The variable value to modify</param>
        /// <param name="isEntireAssignment">Whether the modified value is an entire assignment - meaning no assignment is necessary. This is used for file loading.</param>
        public void AdjustVariableValueIfNecessary(Gum.DataTypes.Variables.VariableSave variableSave, ElementSave container, ref string variableValue, out bool isEntireAssignment)
        {
            isEntireAssignment = false;

            ElementSave categoryContainer;

            Gum.DataTypes.Variables.StateSaveCategory stateSaveCategory;

            string variableType = variableSave.Type;


            if (variableSave.IsState(container, out categoryContainer, out stateSaveCategory))
            {
                string categoryName = "Category";

                if (stateSaveCategory != null)
                {
                    categoryName = stateSaveCategory.Name;
                }
                else
                {
                    categoryName = "VariableState";
                }


                variableValue = GetQualifiedRuntimeTypeFor(categoryContainer) +
                                "." + categoryName + "." + variableSave.Value;
            }

            else if (variableSave.IsEnumeration())
            {
                AdjustEnumerationVariableValue(variableSave, container, ref variableValue, ref variableType);
            }
            else if (variableSave.GetRootName() == "Parent")
            {
                if (container is ComponentSave)
                {
                    variableValue = $"this.ContainedElements.FirstOrDefault(item =>item.Name == \"{variableValue}\") ?? this";
                }
                else
                {
                    variableValue = $"this.ContainedElements.FirstOrDefault(item =>item.Name == \"{variableValue}\")";
                }
            }
            else if (variableSave.IsFile)
            {
                isEntireAssignment = true;

                string fileName = "\"" + variableValue.Replace("\\", "\\\\") + "\"";

                variableValue = "SetProperty(\"" + variableSave.Name + "\", " + fileName + ");";

                ////RenderingLibrary.Content.LoaderManager.Self.Load("fileName", managers);
                //variableValue = "RenderingLibrary.Content.LoaderManager.Self.Load(\"" + variableValue.Replace("\\", "\\\\") + "\", RenderingLibrary.SystemManagers.Default)";
            }

            else if (variableSave.Type == "string")
            {
                variableValue = variableValue.Replace("\\", "\\\\");
                variableValue = variableValue.Replace("\"", "\\\"");
                // do this after replacing the backslashes up above
                variableValue = variableValue.Replace("\n", "\\n");
                variableValue = "\"" + variableValue + "\"";
            }
            else if (variableSave.Type == "float")
            {
                //variableValue = variableValue + "f";
                // convert this using the current language:

                var value = Convert.ToSingle(variableValue, System.Globalization.CultureInfo.CurrentCulture);
                variableValue = value.ToString(System.Globalization.CultureInfo.InvariantCulture) + "f";
            }
            else if (variableSave.Type == "bool")
            {
                variableValue = variableValue.ToLower();
            }
        }
예제 #20
0
        public void CallFillVariableAttributes(VariableSave variableSave, List<Attribute> listToFill)
        {
            if (FillVariableAttributes != null)
            {
                FillVariableAttributes(variableSave, listToFill);

            }
        }
예제 #21
0
        internal List<Attribute> GetAttributesFor(VariableSave variableSave)
        {
            List<Attribute> listToFill = new List<Attribute>();

            CallMethodOnPlugin(
                delegate(PluginBase plugin)
                {
                    plugin.CallFillVariableAttributes(variableSave, listToFill);
                },
                "GetAttributesFor"
            );

            return listToFill;
        }
예제 #22
0
        private bool GetIfShouldGenerateStateVariable(Gum.DataTypes.Variables.VariableSave variable, ElementSave container)
        {
            bool toReturn = true;

            string variableName = variable.GetRootName();



            if (variable.Value == null || !variable.SetsValue)
            {
                toReturn = false;
            }
            // states can't set states on this
            if (variable.IsState(container) && string.IsNullOrEmpty(variable.SourceObject))
            {
                toReturn = false;
            }

            if (toReturn && mVariableNamesToSkipForStates.Contains(variableName))
            {
                toReturn = false;
            }

            bool hasSourceObject = !string.IsNullOrEmpty(variable.SourceObject);

            if (toReturn && hasSourceObject)
            {
                InstanceSave instanceSave = container.GetInstance(variable.SourceObject);

                if (instanceSave == null)
                {
                    toReturn = false;
                }
                else
                {
                    var baseElement = Gum.Managers.ObjectFinder.Self.GetElementSave(instanceSave.BaseType);

                    if (baseElement == null)
                    {
                        toReturn = false;
                    }

                    if (toReturn)
                    {
                        // Gum (just like Glue) keeps variables that aren't needed around.  This allows users to rename things and not lose
                        // important information accidentally.  But because of that we have to make sure that the variable we're working with is
                        // valid for the type of object we're dealing with.
                        var defaultState = baseElement.DefaultState;

                        // October 26, 2018
                        // Bernardo reported
                        // a crash caused by the
                        // RecursiveVariableFinder
                        // being given a state without
                        // a ParentContainer. This is a
                        // sign that the element hasn't
                        // been initialized yet. Elements
                        // should be initialized, but if they're
                        // not, we could just catch it here and initialize
                        // it on the spot. Not sure if I like this solution
                        // or not. It allows code to behave a little unpredictably,
                        // but at the same time, we could simply solve the problem by
                        // initializing here, so I'm going to do that:
                        if (defaultState.ParentContainer == null)
                        {
                            baseElement.Initialize(null);
                        }

                        RecursiveVariableFinder rvf = new RecursiveVariableFinder(defaultState);

                        var foundVariable = rvf.GetVariable(variable.GetRootName());

                        if (foundVariable == null)
                        {
                            // This doesn't exist anywhere in the inheritance chain, so we don't want to generate it:
                            toReturn = false;
                        }
                    }
                }
            }

            if (toReturn && !hasSourceObject)
            {
                // If a variable is part of a component, it better be defined in the base type or else we won't generate it.
                // For example, consider a component that used to inherit from Text. It will have variables for fonts. If that
                // component switches to inheriting from Sprite, those variables will still exist in the XML for that component,
                // but we shouldn't generate any state variables for those variables. So we'll go to the base type and see if those
                // variables exist
                bool isComponent = container is ComponentSave;

                var rootStandardElementSave = Gum.Managers.ObjectFinder.Self.GetRootStandardElementSave(container);

                // If the Container is a Screen, then rootComponent will be null, so we don't need to do anything
                if (rootStandardElementSave == null)
                {
                    toReturn = false;
                }
                else
                {
                    IEnumerable <VariableSave> variablesToCheck;

                    // This code used to get the default state from the rootStandardElementSave,
                    // but the standard element save can have variables missing from the Gum XML,
                    // but it should still support them based on the definition in the StandardElementsManager,
                    // especially if new variables have been added in the future. Therefore, use the StandardElementsManager
                    // rather than the DefaultState:
                    //var rootStandardElementVariables = rootStandardElementSave.DefaultState.Variables;
                    var rootStandardElementVariables = StandardElementsManager.Self
                                                       .DefaultStates[rootStandardElementSave.Name].Variables;

                    if (isComponent)
                    {
                        var component = Gum.Managers.ObjectFinder.Self.GetStandardElement("Component");

                        variablesToCheck = rootStandardElementVariables.Concat(component.DefaultState.Variables).ToList();
                    }
                    else
                    {
                        variablesToCheck = rootStandardElementVariables.ToList();
                    }


                    bool wasMatchFound = variablesToCheck.Any(item => item.Name == variable.GetRootName());
                    toReturn = wasMatchFound;
                }
            }



            return(toReturn);
        }
        private static void AddDimensionsVariables(StateSave stateSave, float defaultWidth, float defaultHeight, DimensionVariableAction dimensionVariableAction)
        {
            stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "float", Value = defaultWidth, Name = "Width", Category = "Dimensions" });

            var defaultValue = DimensionUnitType.Absolute;

            if(dimensionVariableAction == DimensionVariableAction.DefaultToPercentageOfFile)
            {
                defaultValue = DimensionUnitType.PercentageOfSourceFile;
            }

            VariableSave variableSave = new VariableSave { SetsValue = true, Type = typeof(DimensionUnitType).Name, Value = defaultValue, Name = "Width Units", Category = "Dimensions" };
            if (dimensionVariableAction == DimensionVariableAction.ExcludeFileOptions)
            {
                variableSave.ExcludedValuesForEnum.Add(DimensionUnitType.PercentageOfSourceFile);
            }
            stateSave.Variables.Add(variableSave);



            stateSave.Variables.Add(new VariableSave { SetsValue = true, Type = "float", Value = defaultHeight, Name = "Height", Category = "Dimensions" });

            variableSave = new VariableSave { SetsValue = true, Type = typeof(DimensionUnitType).Name, Value = defaultValue, Name = "Height Units", Category = "Dimensions" };
            if (dimensionVariableAction == DimensionVariableAction.ExcludeFileOptions)
            {
                variableSave.ExcludedValuesForEnum.Add(DimensionUnitType.PercentageOfSourceFile);
            }
            stateSave.Variables.Add(variableSave);
        }
예제 #24
0
 internal bool GetIfVariableIsExcluded(VariableSave defaultVariable, RecursiveVariableFinder rvf)
 {
     if (VariableExcluded == null)
     {
         return false;
     }
     else
     {
         return VariableExcluded(defaultVariable, rvf);
     }
 }
 private static void AddParentVariables(StateSave variables)
 {
     VariableSave variableSave = new VariableSave();
     variableSave.SetsValue = true;
     variableSave.Type = "string";
     variableSave.Name = "Parent";
     variableSave.CanOnlyBeSetInDefaultState = true;
     variableSave.CustomTypeConverter = new AvailableInstancesConverter() { IncludeScreenBounds = true };
     variables.Variables.Add(variableSave);
 }
예제 #26
0
        /// <summary>
        /// Attempts to get the value for the argument variableName, or null if not found.
        /// </summary>
        /// <param name="variableName">The qualified variable name</param>
        /// <returns>The value found, or null</returns>
        public object GetValue(string variableName)
        {
            ////////////////////Early Out////////////////
            if (ParentContainer == null)
            {
                return(null);
            }
            //////////////////End Early Out//////////////

            // Check for reserved stuff
            if (variableName == "Name")
            {
                return(ParentContainer.Name);
            }
            else if (variableName == "Base Type")
            {
                if (string.IsNullOrEmpty(ParentContainer.BaseType))
                {
                    return(null);
                }
                else
                {
                    string baseType = ParentContainer.BaseType;
                    StandardElementTypes returnValue;

                    if (Enum.TryParse <StandardElementTypes>(baseType, out returnValue))
                    {
                        return(returnValue);
                    }
                    else
                    {
                        return(baseType);
                    }
                }
            }

            if (ToolsUtilities.StringFunctions.ContainsNoAlloc(variableName, '.'))
            {
                string instanceName = variableName.Substring(0, variableName.IndexOf('.'));

                ElementSave  elementSave  = ParentContainer;
                InstanceSave instanceSave = null;

                if (elementSave != null)
                {
                    instanceSave = elementSave.GetInstance(instanceName);
                }

                if (instanceSave != null)
                {
                    // This is a variable on an instance
                    if (variableName.EndsWith(".Name"))
                    {
                        return(instanceSave.Name);
                    }
                    else if (variableName.EndsWith(".Base Type"))
                    {
                        return(instanceSave.BaseType);
                    }
                    else if (variableName.EndsWith(".Locked"))
                    {
                        return(instanceSave.Locked);
                    }
                }
            }

            VariableSave variableState = GetVariableSave(variableName);


            // If the user hasn't set this variable on this state, it'll be null. So let's just display null
            // for now.  Eventually we'll display a variable plus some kind of indication that it's an unset variable.
            if (variableState == null || variableState.SetsValue == false)
            {
                VariableListSave variableListSave = GetVariableListSave(variableName);
                if (variableListSave != null)
                {
                    return(variableListSave.ValueAsIList);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(variableState.Value);
            }
        }
        private void AddAssignmentForInterpolationForVariable(ICodeBlock curBlock, VariableSave variable, ElementSave container)
        {
            string memberNameInCode = variable.MemberNameInCode(container, mVariableNamesToReplaceForStates);
            ElementSave categoryContainer;
            StateSaveCategory stateSaveCategory;

            if (variable.IsState(container, out categoryContainer, out stateSaveCategory, recursive:false) && !string.IsNullOrEmpty(variable.SourceObject))
            {
                string line = string.Format(
                    "{0}.InterpolateBetween({1}FirstValue, {1}SecondValue, interpolationValue);",
                    SaveObjectExtensionMethods.InstanceNameInCode( variable.SourceObject), memberNameInCode.Replace(".", ""));
                curBlock.Line(line);
            }
            else
            {

                switch (variable.Type)
                {
                    case "int":
                        curBlock.Line(string.Format("{0} = FlatRedBall.Math.MathFunctions.RoundToInt({1}FirstValue* (1 - interpolationValue) + {1}SecondValue * interpolationValue);",
                            memberNameInCode, memberNameInCode.Replace(".", "")));

                        break;
                    case "float":
                    case "double":
                        curBlock.Line(string.Format("{0} = {1}FirstValue * (1 - interpolationValue) + {1}SecondValue * interpolationValue;",
                            memberNameInCode, memberNameInCode.Replace(".", "")));
                        break;
                }
            }
        }